<?php
	require_once APPPATH . 'controllers/base_controllers/base_controller.php';

	class Member_registration extends Base_controller
	{
		public static $REGISTRATION_TEMPLATE = 'templates/registration/registration_template';		
		
		
		public function __construct()
		{
			parent::__construct();
			
			$this->load->model('values/member_registration_value');
			$this->load->model('values/cwr_registrant_member_homepage_value');
			$this->load->model('values/person_value');
			$this->load->model('values/member_info_value');
		}
		
		
		public function step1()
		{
			$this->load->model('proxies/Walk_proxy');
/*			
			//Create Registration Value In Session
			$memberRegistrationValue = new Member_registration_value();
			
			$this->session->unset_userdata('member_registration_value');
			$this->session->set_userdata('member_registration_value', serialize($memberRegistrationValue));
*/			
            $data['title'] = $this->Walk_proxy->getCurrentYear().'-'.($this->Walk_proxy->getCurrentYear()+1).' New Member Registration ';
            $data['curyear'] = $this->Walk_proxy->getCurrentYear();
            
            if ($this->Walk_proxy->isRegistrationOpen())
            {
    			$data['view'] = 'cmb/register/member_collect_person_view';
            }
            else
            {
                $datesBV = $this->Walk_proxy->getCurrentBVEventDates($this->Walk_proxy->getCurrentYear());
                $data['open_date'] = $datesBV[2];               
                $data['view'] = 'cmb/register/registration_closed_view';
            }
			
			$this->load->view( self::$REGISTRATION_TEMPLATE, $data );
		}
		
		
		public function step1_process()
		{
			$this->load->model('proxies/Person_proxy');
			$this->load->model('proxies/Walk_proxy');
			$this->load->model('proxies/Paypal_proxy');
			$this->load->library('encrypt');
			
			//Save To Session...
			$person = new Person_value();
			$memberInfo = new Member_info_value();
			
			//New member
			//$newMember = $this->input->post('newMember');
			$newMember = "yes";
			
			//Which CMB center 
			$memberInfo->setCMBCenter( $this->input->post('cmbCenter') );
			$cmbCenter = $this->input->post('cmbCenter');
						
			//Get current registration fee
			$regFee = $this->Walk_proxy->getCurrentRegAmount( $this->input->post('cmbCenter') );
			$memberInfo->setRegistrationFee( $regFee );
			if($this->config->item('debug') == TRUE)
			    echo "Registration Fee: " . $regFee . "<br/>";
			
			if( $this->input->post('cmbCenter') == "Andover" )
			{							
				//Primary member
				$person->setFirstName( trim($this->input->post('firstName')) );
				$person->setLastName( trim($this->input->post('lastName')) );
				$person->setSecretQuestion( trim($this->input->post('question')) );
				$person->setSecretPhrase( trim($this->input->post('secretPhrase')) );
				$displayName = $person->getFirstName() .' '. $person->getLastName();
				$memberInfo->setDisplayName( $displayName );
				$person->setGender( $this->input->post('gender') );
				$person->setEmail1( $this->input->post('primaryEmail') );
				$person->setPhone1( $this->input->post('homePhoneNumber') );
				$person->setPhone2( $this->input->post('mobilePhoneNumber') );
				$person->setOrgName( trim($this->input->post('company')) );
				$person->setPrimaryAttendSatsang( $this->input->post('primaryAttendSatsang') );
				$person->setAddress1( trim($this->input->post('homeAddress1')) );
				$person->setAddress2( trim($this->input->post('homeAddress2')) );
				$person->setCity( trim($this->input->post('city')) );
				$person->setState( $this->input->post('state') );
				$person->setZip( $this->input->post('zipCode') );
				$volInterestArray = array();
				for( $i = 1; $i <= 12; $i++ )
				{
					if( isset( $_POST['volArea' . $i] ) )
					{
				   	array_push( $volInterestArray, $this->input->post('volArea' . $i) );
					}
				}
				$person->setVolunteerInterests( $volInterestArray );
									
				//Spouse
				$memberInfo->setSpouseFirstName( trim($this->input->post('spouseFirstName')) );
				$memberInfo->setSpouseLastName( trim($this->input->post('spouseLastName')) );
				$memberInfo->setSpouseGender( $this->input->post('spouseGender') );
				$memberInfo->setSpouseEmail( $this->input->post('spouseEmail') );
				$memberInfo->setSpouseHomePhone( $this->input->post('spousePhone') );
				$memberInfo->setSpouseMobilePhone( $this->input->post('spouseMobilePhone') );
				$memberInfo->setSpouseAttendSatsang( $this->input->post('primaryAttendSatsang') );
				$spouseVolInterestArray = array();
				for( $i = 1; $i <= 12; $i++ )
				{
					if( isset( $_POST['spouseVolArea' . $i] ) )
					{
				   	array_push( $spouseVolInterestArray, $this->input->post('spouseVolArea' . $i) );
					}
				}
				$memberInfo->setSpouseVolunteerInterests( $spouseVolInterestArray );
			
				//Household
				$lifeMember = "no";
				//$lifeMember = $this->input->post('lifeMember');
				$memberInfo->setLifeMember( $lifeMember );

				//$donationopt = $this->input->post('donationopt');
				//if ($donationopt != "yes")
					//$donationamount = "0.0";
				//else
				
				$donationamount = $this->input->post('donationamount');
				if (is_numeric($donationamount))
				{
					if ($donationamount < 0)
						$donationamount = 0;
				}
				else
					$donationamount = 0;
				
				$memberInfo->setDonation( $donationamount );
										
				//Children
				$numChildren = $this->input->post('numChildren');
				$memberInfo->setNumberOfChildren( $numChildren );
			
				$childArray = array(); //Stores all children
				for( $i = 1; $i <= $numChildren; $i++ )
				{
					$childInfoArray = array(); //Stores attributes per child
					$childLangArray = array(); //Stores language class
					$childLangLevelArray = array(); //Stores language class level
                    $childLangSessionArray = array(); //Stores language session
													
					//Add attributes for a child
					array_push( $childInfoArray, trim($this->input->post('childFN' . $i)) );
					array_push( $childInfoArray, trim($this->input->post('childLN' . $i)) );
					array_push( $childInfoArray, $this->input->post('childG' . $i) );
					if ($this->input->post('childEM' . $i) == "")
					{
						array_push( $childInfoArray, $this->input->post('primaryEmail') );
					}
					else
					{						
						array_push( $childInfoArray, $this->input->post('childEM' . $i) );
					}
					array_push( $childInfoArray, $this->input->post('childDOB' . $i) );
					array_push( $childInfoArray, $this->input->post('childGrade' . $i) );
					array_push( $childInfoArray, $this->input->post('childSession' . $i) );

					//Add language classes
				   	if ($this->input->post('child' . $i . 'Lang') != "None")
					{
						array_push( $childLangArray, $this->input->post('child' . $i . 'Lang') );
						
						$langlevel = "beginner";
						if($this->input->post('child' . $i . 'LangLevel1') != "None")
							$langlevel = $this->input->post('child' . $i . 'LangLevel1');
						
						array_push( $childLangLevelArray, $langlevel );
                        
                        array_push( $childLangSessionArray, $this->input->post('child' . $i . 'LangSession') );
					}
				
					//Add entire child info array
					array_push($childArray, $childInfoArray);
				
					//Add entire child language array
					array_push($childArray, $childLangArray);
				
					//Add entire child language level array
					array_push($childArray, $childLangLevelArray);

                    //Add entire child language session array
                    array_push($childArray, $childLangSessionArray);
				}
			}
			else
			{
				//Primary member
				$person->setFirstName( trim($this->input->post('firstName1')) );
				$person->setLastName( trim($this->input->post('lastName1')) );
				$person->setSecretQuestion( trim($this->input->post('question1')) );
				$person->setSecretPhrase( trim($this->input->post('secretPhrase1')) );
				$displayName = $person->getFirstName() .' '. $person->getLastName();
				$memberInfo->setDisplayName( $displayName );
				$person->setGender( $this->input->post('gender1') );
				$person->setEmail1( $this->input->post('primaryEmail1') );
				$person->setPhone1( $this->input->post('homePhoneNumber1') );
				$person->setPhone2( $this->input->post('mobilePhoneNumber1') );
				$person->setOrgName( trim($this->input->post('company1')) );
				$person->setPrimaryAttendSatsang( 'PM' );
				$person->setAddress1( trim($this->input->post('homeAddress1mw')) );
				$person->setAddress2( trim($this->input->post('homeAddress2mw')) );
				$person->setCity( trim($this->input->post('city1')) );
				$person->setState( $this->input->post('state1') );
				$person->setZip( $this->input->post('zipCode1') );
				$volInterestArray = array();
				for( $i = 1; $i <= 12; $i++ )
				{
					if( isset( $_POST['volArea' . $i . 'mw'] ) )
					{
				   	array_push( $volInterestArray, $this->input->post('volArea' . $i . 'mw') );
					}
				}
				$person->setVolunteerInterests( $volInterestArray );
									
				//Spouse
				$memberInfo->setSpouseFirstName( trim($this->input->post('spouseFirstName1')) );
				$memberInfo->setSpouseLastName( trim($this->input->post('spouseLastName1')) );
				$memberInfo->setSpouseGender( $this->input->post('spouseGender1') );
				$memberInfo->setSpouseEmail( $this->input->post('spouseEmail1') );
				$memberInfo->setSpouseHomePhone( $this->input->post('spousePhone1') );
				$memberInfo->setSpouseMobilePhone( $this->input->post('spouseMobilePhone1') );
				$memberInfo->setSpouseAttendSatsang( 'PM' );
				$spouseVolInterestArray = array();
				for( $i = 1; $i <= 12; $i++ )
				{
					if( isset( $_POST['spouseVolArea' . $i . 'mw'] ) )
					{
				   	array_push( $spouseVolInterestArray, $this->input->post('spouseVolArea' . $i . 'mw') );
					}
				}
				$memberInfo->setSpouseVolunteerInterests( $spouseVolInterestArray );
			
				//Household
				$lifeMember = "no";
				//$lifeMember = $this->input->post('lifeMember1');
				$memberInfo->setLifeMember( $lifeMember );

				//$donationopt = $this->input->post('donationopt1');
				//if ($donationopt != "yes")
					//$donationamount = "0.0";
				//else
				
				$donationamount = $this->input->post('donationamount1');
				if (is_numeric($donationamount))
				{
					if ($donationamount < 0)
						$donationamount = 0;
				}
				else
					$donationamount = 0;
				
				$memberInfo->setDonation( $donationamount );
						
				//Children
				$numChildren = $this->input->post('numChildren1');
				$memberInfo->setNumberOfChildren( $numChildren );
			
				$childArray = array(); //Stores all children
				for( $i = 1; $i <= $numChildren; $i++ )
				{
					$childInfoArray = array(); //Stores attributes per child
					$childLangArray = array(); //Stores language class
					$childLangLevelArray = array(); //Stores language class level
                    $childLangSessionArray = array(); //Stores language session
													
					//Add attributes for a child
					array_push( $childInfoArray, trim($this->input->post('childFNmw' . $i)) );
					array_push( $childInfoArray, trim($this->input->post('childLNmw' . $i)) );
					array_push( $childInfoArray, $this->input->post('childGmw' . $i) );
					if ($this->input->post('childEMmw' . $i) == "")
					{
						array_push( $childInfoArray, $this->input->post('primaryEmail1') );
					}
					else
					{						
						array_push( $childInfoArray, $this->input->post('childEMmw' . $i) );
					}
					array_push( $childInfoArray, $this->input->post('childDOBmw' . $i) );
					array_push( $childInfoArray, $this->input->post('childGrademw' . $i) );
					array_push( $childInfoArray, 'PM' );

					//Add language classes
				   	if ($this->input->post('child' . $i . 'Langmw') != "None")
					{
						array_push( $childLangArray, $this->input->post('child' . $i . 'Langmw') );
						
						$langlevel = "beginner";
						if($this->input->post('child' . $i . 'LangLevelmw1') != "None")
							$langlevel = $this->input->post('child' . $i . 'LangLevelmw1');
						
						array_push( $childLangLevelArray, $langlevel );

                        array_push( $childLangSessionArray, "PM" );
					}

					//Add entire child info array
					array_push($childArray, $childInfoArray);
				
					//Add entire child language array
					array_push($childArray, $childLangArray);
				
					//Add entire child language level array
					array_push($childArray, $childLangLevelArray);

                    //Add entire child language session array
                    array_push($childArray, $childLangSessionArray);
				}
			}
			
			$memberInfo->setChildrenInfo( $childArray );

			$continueWithRegistration = TRUE;

			if( $newMember == "yes" )
			{
				//New Member
				$checkPersonExists = $this->Person_proxy->primarypersonExists($person);				
				if ( $checkPersonExists != 0 )
				{
					//Primary person exists in database, go back
					$primaryPersonId = $checkPersonExists;
					if($this->config->item('debug') == TRUE)
					    echo "Primary member already exists: " . $primaryPersonId . "<br/>";
					//Go to an error page and go back to registration
					redirect( base_url() . 'cmb/member_registration/member_registered/');				
				}
				else
				{
					//Do insert
					$primaryPersonId = $this->Person_proxy->insertPrimaryPerson( $person );
					if ( $primaryPersonId == 0)
					{
						if($this->config->item('debug') == TRUE)
						    echo "Error inserting primary person to database <br/>";
					}
					
					//Generate credentials
					$person->setPersonId($primaryPersonId);
					$personCredentials = $this->Person_proxy->createPersonCredentials($primaryPersonId);
					if(count($personCredentials) == 2)
					{
						$rv = $this->Person_proxy->updatePersonCredentials($primaryPersonId, $personCredentials);
						$person->setUserName($personCredentials[0]);
						$person->setPassword($personCredentials[1]);
					}
					
					if($this->config->item('debug') == TRUE)
					    echo "Inserted Primary Person: " . $primaryPersonId . "<br/>";

					//Get household_id (based on primary person)
					$householdId = $this->Person_proxy->getHouseholdID( $primaryPersonId );
					if ($householdId == 0)
					{
						//Primary person is not part of a household, so create household
						$householdId = $this->Person_proxy->insertHousehold( $person );
						if($this->config->item('debug') == TRUE)
						    echo "Created household" . "<br/>";
					}
					if($this->config->item('debug') == TRUE)
					    echo "Household ID: " . $householdId . "<br/>";
				
					//Get person_id for spouse and do insert or update to person
					if ($memberInfo->getSpouseFirstName() != "")
			   		{
						$spousepersonId = $this->Person_proxy->personExists($memberInfo->getSpouseFirstName(), $memberInfo->getSpouseLastName(), $memberInfo->getSpouseEmail());
						if ($spousepersonId == 0)
						{
							//Spouse does not exist, insert into person
							$spousepersonId = $this->Person_proxy->insertPerson($person, $memberInfo->getSpouseFirstName(), $memberInfo->getSpouseLastName(), $memberInfo->getSpouseGender(), $memberInfo->getSpouseEmail(), $memberInfo->getSpouseHomePhone(), $memberInfo->getSpouseMobilePhone(), $memberInfo->getSpouseVolunteerInterests());
							if($this->config->item('debug') == TRUE)
							    echo "Inserted Spouse Person ID: " . $spousepersonId . "<br/>";
						
							//Create credentials and update
							$personCredentials = $this->Person_proxy->createPersonCredentials($spousepersonId);
							if(count($personCredentials) == 2)
							{
								$rv = $this->Person_proxy->updatePersonCredentials($spousepersonId, $personCredentials);
							}
						}
						else
						{
							//Update spouse info in person
							$spousepersonId = $this->Person_proxy->updatePerson($person, $spousepersonId, $memberInfo->getSpouseGender(), $memberInfo->getSpouseEmail(), $memberInfo->getSpouseHomePhone(), $memberInfo->getSpouseMobilePhone(), $memberInfo->getSpouseVolunteerInterests());
							if($this->config->item('debug') == TRUE)
							    echo "Updated Spouse Person ID: " . $spousepersonId . "<br/>";
						
							if($this->Person_proxy->personHasCredentials($spousepersonId))
								$personCredentials = $this->Person_proxy->getPersonCredentials( $spousepersonId );
							else
							{
								$personCredentials = $this->Person_proxy->createPersonCredentials($spousepersonId);
								if(count($personCredentials) == 2)
								{
									$rv = $this->Person_proxy->updatePersonCredentials($spousepersonId, $personCredentials);
								}
							}
						}

						//Check if spouse is already in household and insert if not
						$temphhId = $this->Person_proxy->getHouseholdID( $spousepersonId );
						if ($temphhId == 0)
						{
							//Add spouse to household
							$temphhId = $this->Person_proxy->insertSpouseHousehold( $spousepersonId, $householdId );
							if($this->config->item('debug') == TRUE)
							    echo "Added spouse to household" . "<br/>";
						}
					}
					else
					{
						if($this->config->item('debug') == TRUE)
						    echo "No Spouse <br/>";
					} //if ($memberInfo->getSpouseFirstName() != "")
								
					//Get person_id's for children and do insert or update to person
					$childPersonIdArray = array();
					for( $i = 0; $i < $numChildren; $i++ )
					//foreach ($childArray as $childInfoArray)
					{
						$idx1 = 4*$i;
						$idx2 = 4*$i + 1;
						$idx3 = 4*$i + 2;
                        $idx4 = 4*$i + 3;
						$childInfoArray = $childArray[$idx1];
						$childLangArray = $childArray[$idx2];
						$childLangLevelArray = $childArray[$idx3];
                        $childLangSessionArray = $childArray[$idx4];
						if($this->config->item('debug') == TRUE)
						{
							echo $childInfoArray[0] . "<br/>"; //First Name
							echo $childInfoArray[1] . "<br/>"; //Last Name
							echo $childInfoArray[2] . "<br/>"; //Gender
							echo $childInfoArray[3] . "<br/>"; //EMail
							echo $childInfoArray[4] . "<br/>"; //DOB
							echo $childInfoArray[5] . "<br/>"; //Grade
							echo $childInfoArray[6] . "<br/>"; //Session
							echo "Languages: <br/>";
						}
						for( $j = 0; $j < count($childLangArray); $j++ )
						{
							if($this->config->item('debug') == TRUE)
							    echo $childLangArray[$j] . " - " . $childLangLevelArray[$j] . "<br/>";
						}
											
						$childPersonId = $this->Person_proxy->personExists($childInfoArray[0], $childInfoArray[1], $childInfoArray[3]);
						if ( $childPersonId != 0)
						{
							//Child exists in database, do an update
							$childPersonId = $this->Person_proxy->updateChildPerson( $person, $childPersonId, $childInfoArray[2], $childInfoArray[3], $childInfoArray[4] );
					    	if($this->config->item('debug') == TRUE)
							    echo "Updated Child Person: " . $childPersonId . "," . $childInfoArray[0] . "," . $childInfoArray[1] . "<br/>";
						}
						else
						{
							//Child does not exist in database, do an insert
							$childPersonId = $this->Person_proxy->insertChildPerson( $person, $childInfoArray[0], $childInfoArray[1], $childInfoArray[2], $childInfoArray[3], $childInfoArray[4] );
					   	    if($this->config->item('debug') == TRUE)
							    echo "Inserted Child Person: " . $childPersonId . "," . $childInfoArray[0] . "," . $childInfoArray[1] . "<br/>";
						}
					
						array_push( $childPersonIdArray, $childPersonId );

						//Check if child is already in household and insert if not
						$temphhId = $this->Person_proxy->getHouseholdID( $childPersonId );
						if ($temphhId == 0)
						{
							//Add child to household
							$householdId = $this->Person_proxy->insertChildHousehold( $childPersonId, $householdId );
							if($this->config->item('debug') == TRUE)
							    echo "Added child to household" . "<br/>";
						}
					} //foreach ($childArray as $childInfoArray
				} //if ( $checkPersonExists != 0 )
			}
			else
			{
				//Existing Member
				//See if the primary member already exists
				$checkPersonExists = $this->Person_proxy->primarypersonExists($person);				
				if ( $checkPersonExists != 0 )
				{
					//Primary person exists in database, do updates
					$primaryPersonId = $checkPersonExists;
					$person->setPersonId($primaryPersonId);
					//For future existing person registration
					/*
					if($this->Person_proxy->personHasSecretPhrase($primaryPersonId) == FALSE)
					{
						$person->setSecretPhrase($this->encrypt->get_random_password());
					}
					else
					{
						$person->setSecretPhrase($this->Person_proxy->getPersonSecretPhrase($primaryPersonId));
					} */
					$primaryPersonId = $this->Person_proxy->updatePrimaryPerson( $person );
					if($this->Person_proxy->personHasCredentials($primaryPersonId) == FALSE)
					{
						$personCredentials = $this->Person_proxy->createPersonCredentials($primaryPersonId);
						if(count($personCredentials) == 2)
						{
							$rv = $this->Person_proxy->updatePersonCredentials($primaryPersonId, $personCredentials);
							$person->setUserName($personCredentials[0]);
							$person->setPassword($personCredentials[1]);
						}
					}
					else
					{
						$personCredentials = $this->Person_proxy->getPersonCredentials($primaryPersonId);
						if(count($personCredentials) == 2)
						{
							$person->setUserName($personCredentials[0]);
							$person->setPassword($personCredentials[1]);
						}
					}
					if($this->config->item('debug') == TRUE)
					    echo "Updated Primary Person: " . $primaryPersonId . "<br/>";			
				}
				else
				{
					if($this->config->item('debug') == TRUE)
					    echo "Primary person is not in database <br/>";
					//Do insert
					$primaryPersonId = $this->Person_proxy->insertPrimaryPerson( $person );
					if ( $primaryPersonId == 0)
					{
						if($this->config->item('debug') == TRUE)
						    echo "Error inserting primary person to database <br/>";
					}
					$person->setPersonId($primaryPersonId);
					
					//Generate credentials
					$personCredentials = $this->Person_proxy->createPersonCredentials($primaryPersonId);
					if(count($personCredentials) == 2)
					{
						$rv = $this->Person_proxy->updatePersonCredentials($primaryPersonId, $personCredentials);
						$person->setUserName($personCredentials[0]);
						$person->setPassword($personCredentials[1]);
					}
					
					//Send admin alert indicating that could not find existing member and
					//and inserted a new person entry
				} //if ( $checkPersonExists != 0 )

				//Get household_id (based on primary person)
				$householdId = $this->Person_proxy->getHouseholdID( $primaryPersonId );
				if ($householdId == 0)
				{
					//Primary person is not part of a household, so create household
					$householdId = $this->Person_proxy->insertHousehold( $person );
					if($this->config->item('debug') == TRUE)
					    echo "Created household" . "<br/>";
				}
				if($this->config->item('debug') == TRUE)
				    echo "Household ID: " . $householdId . "<br/>";
				
				//Get person_id for spouse and do insert or update to person
				if ($memberInfo->getSpouseFirstName() != "")
			    {
					$spousepersonId = $this->Person_proxy->personExists($memberInfo->getSpouseFirstName(), $memberInfo->getSpouseLastName(), $memberInfo->getSpouseEmail());
					if ($spousepersonId == 0)
					{
						//Spouse does not exist, insert into person
						$spousepersonId = $this->Person_proxy->insertPerson($person, $memberInfo->getSpouseFirstName(), $memberInfo->getSpouseLastName(), $memberInfo->getSpouseGender(), $memberInfo->getSpouseEmail(), $memberInfo->getSpouseHomePhone(), $memberInfo->getSpouseMobilePhone(), $memberInfo->getSpouseVolunteerInterests());
						if($this->config->item('debug') == TRUE)
						    echo "Inserted Spouse Person ID: " . $spousepersonId . "<br/>";					
						
						//Create credentials and update
						$personCredentials = $this->Person_proxy->createPersonCredentials($spousepersonId);
						if(count($personCredentials) == 2)
						{
							$rv = $this->Person_proxy->updatePersonCredentials($spousepersonId, $personCredentials);
						}
					}
					else
					{
						//Update spouse info in person
						$spousepersonId = $this->Person_proxy->updatePerson($person, $spousepersonId, $memberInfo->getSpouseGender(), $memberInfo->getSpouseEmail(), $memberInfo->getSpouseHomePhone(), $memberInfo->getSpouseMobilePhone(), $memberInfo->getSpouseVolunteerInterests());
						if($this->config->item('debug') == TRUE)
						    echo "Updated Spouse Person ID: " . $spousepersonId . "<br/>";
						
						if($this->Person_proxy->personHasCredentials($spousepersonId))
							$personCredentials = $this->Person_proxy->getPersonCredentials( $spousepersonId );
						else
						{
							$personCredentials = $this->Person_proxy->createPersonCredentials($spousepersonId);
							if(count($personCredentials) == 2)
							{
								$rv = $this->Person_proxy->updatePersonCredentials($spousepersonId, $personCredentials);
							}
						}
					}

					//Check if spouse is already in household and insert if not
					$temphhId = $this->Person_proxy->getHouseholdID( $spousepersonId );
					if ($temphhId == 0)
					{
						//Add spouse to household
						$temphhId = $this->Person_proxy->insertSpouseHousehold( $spousepersonId, $householdId );
						if($this->config->item('debug') == TRUE)
						    echo "Added spouse to household" . "<br/>";
					}
				}
				else
				{
					if($this->config->item('debug') == TRUE)
					    echo "No Spouse <br/>";
				} //if ($memberInfo->getSpouseFirstName() != "")
								
				//Get person_id's for children and do insert or update to person
				$childPersonIdArray = array();
				for( $i = 0; $i < $numChildren; $i++ )
				//foreach ($childArray as $childInfoArray)
				{
                    $idx1 = 4*$i;
                    $idx2 = 4*$i + 1;
                    $idx3 = 4*$i + 2;
                    $idx4 = 4*$i + 3;
					$childInfoArray = $childArray[$idx1];
					$childLangArray = $childArray[$idx2];
					$childLangLevelArray = $childArray[$idx3];
                    $childLangSessionArray = $childArray[$idx4];
					if($this->config->item('debug') == TRUE)
					{
						echo $childInfoArray[0] . "<br/>"; //First Name
						echo $childInfoArray[1] . "<br/>"; //Last Name
						echo $childInfoArray[2] . "<br/>"; //Gender
						echo $childInfoArray[3] . "<br/>"; //EMail
						echo $childInfoArray[4] . "<br/>"; //DOB
						echo $childInfoArray[5] . "<br/>"; //Grade
						echo $childInfoArray[6] . "<br/>"; //Session
						echo "Languages: <br/>";
					}
					for( $j = 0; $j < count($childLangArray); $j++ )
					{
						if($this->config->item('debug') == TRUE)
						    echo $childLangArray[$j] . " - " . $childLangLevelArray[$j] . "<br/>";
					}
					
					$childPersonId = $this->Person_proxy->personExists($childInfoArray[0], $childInfoArray[1], $childInfoArray[3]);
					if($this->config->item('debug') == TRUE)
					    echo "Processing Child Person: " . $childPersonId . "<br/>";
					if ( $childPersonId != 0)
					{
						//Child exists in database, do an update
						$childPersonId = $this->Person_proxy->updateChildPerson( $person, $childPersonId, $childInfoArray[2], $childInfoArray[3], $childInfoArray[4] );
					    if($this->config->item('debug') == TRUE)
						    echo "Updated Child Person: " . $childPersonId . "," . $childInfoArray[0] . "," . $childInfoArray[1] . "<br/>";
					}
					else
					{
						//Child does not exist in database, do an insert
						$childPersonId = $this->Person_proxy->insertChildPerson( $person, $childInfoArray[0], $childInfoArray[1], $childInfoArray[2], $childInfoArray[3], $childInfoArray[4] );
					    if($this->config->item('debug') == TRUE)
						    echo "Inserted Child Person: " . $childPersonId . "," . $childInfoArray[0] . "," . $childInfoArray[1] . "<br/>";
					}
					
					array_push( $childPersonIdArray, $childPersonId );

					//Check if child is already in household and insert if not
					$temphhId = $this->Person_proxy->getHouseholdID( $childPersonId );
					if ($temphhId == 0)
					{
						//Add child to household
						$temphhId = $this->Person_proxy->insertChildHousehold( $childPersonId, $householdId );
						if($this->config->item('debug') == TRUE)
						    echo "Added child to household" . "<br/>";
					}
				} //foreach ($childArray as $childInfoArray)
			} //if( $newMember == "yes" )
					 
			//At this point we personId's for primary, spouse and children and
			//they have all been added to a household (if needed).
			$memberInfo->setHouseholdId($householdId);
			$currentyear = $this->Walk_proxy->getCurrentYear();
			$cmbCenterId = $this->Walk_proxy->getCMBCenterId($memberInfo->getCMBCenter());
			$hhRegistered = $this->Walk_proxy->isHouseholdRegistered($householdId, $currentyear, $cmbCenterId);
			if ( $hhRegistered == TRUE )
			{
				//Household is already registered
				if($this->config->item('debug') == TRUE)
				    echo "Household: " . $householdId . " is registered for ".$currentyear . "<br/>";

				$cmbRegHistoryId = $this->Walk_proxy->getCMBRegistration( $householdId, $currentyear, $cmbCenterId );
				
				if ($cmbRegHistoryId < 1)
					redirect( base_url() . 'cmb/member_registration/registration_error/');
				
				$memberInfo->setCMBRegHistoryId($cmbRegHistoryId);
				
				$regpaid = $this->Walk_proxy->isRegistrationPaid($cmbRegHistoryId);
				if ($regpaid)
					$continueWithRegistration = FALSE;
					
				//echo "Household: " . $householdId . " is registered for ".$currentyear . " , " .$cmbRegHistoryId . "<br/>";
				//die; 				
			}
			else
			{
				if($this->config->item('debug') == TRUE)
				    echo "Household: " . $householdId . " is not registered for ".$currentyear . "<br/>";
				$cmbRegHistoryId = $this->Walk_proxy->insertCMBRegistration( $householdId, $cmbCenterId, $regFee, $currentyear, $person->getPrimaryAttendSatsang(), $memberInfo );
				$memberInfo->setCMBRegHistoryId($cmbRegHistoryId);
				if($this->config->item('debug') == TRUE)
				    echo "Household: " . $householdId . " has been registered: ".$cmbRegHistoryId . "<br/>";
				
				//echo "Household: " . $householdId . " is registered for ".$currentyear . " , " .$cmbRegHistoryId . "<br/>";
				//die; 				
			}
			
			//Check if children in bv_reg_history, if not insert
			$dates = $this->Walk_proxy->getCurrentBVEventDates($currentyear);
			if($this->config->item('debug') == TRUE)
			{
				echo $dates[0] . "<br/>";
				echo $dates[1] . "<br/>";
				echo $dates[2] . "<br/>";
				echo $dates[3] . "<br/>";
			}
			for( $i = 0; $i < $numChildren; $i++ )
			{
				$childPersonId = $childPersonIdArray[$i];
				$idx1 = 4*$i;
				$childInfoArray = $childArray[$idx1];
				$isChildRegistered = $this->Walk_proxy->isChildRegisteredBV( $childPersonId, $currentyear, $cmbCenterId );
				if ($isChildRegistered == TRUE)
				{
					if($this->config->item('debug') == TRUE)
					    echo "Child: " . $childPersonId . " is registered for ".$currentyear . "<br/>";
				}
				else
				{
					if($this->config->item('debug') == TRUE)
					    echo "Child: " . $childPersonId . " is NOT registered for ".$currentyear . "<br/>";
					$bvRegHistoryId = $this->Walk_proxy->insertBVRegistration( $childPersonId, $cmbCenterId, $currentyear, $dates, $childInfoArray );
					if($this->config->item('debug') == TRUE)
					    echo "Inserted Child Person: " . $bvRegHistoryId . " for ".$currentyear . "<br/>";
				}
			}

			//Check if language preference in lang_reg_history, if not insert
			$dates = $this->Walk_proxy->getCurrentLangEventDates();
			if($this->config->item('debug') == TRUE)
			{
				echo $dates[0] . "<br/>";
				echo $dates[1] . "<br/>";
				echo $dates[2] . "<br/>";
				echo $dates[3] . "<br/>";
			}
			for( $i = 0; $i < $numChildren; $i++ )
			{
				$childPersonId = $childPersonIdArray[$i];
				$idx1 = 4*$i;
				$idx2 = 4*$i + 1;
				$idx3 = 4*$i + 2;
                $idx3 = 4*$i + 3;
				$childInfoArray = $childArray[$idx1];
				$childLangArray = $childArray[$idx2];
				$childLangLevelArray = $childArray[$idx3];
                $childLangSessionArray = $childArray[$idx3];
				for( $j = 0; $j < count($childLangArray); $j++ )
				{
				 	$langId = $this->Walk_proxy->getLangId($childLangArray[$j]);
					$isChildRegistered = $this->Walk_proxy->isChildRegisteredLang( $childPersonId, $currentyear, $cmbCenterId, $langId );
				
					if ($isChildRegistered == TRUE)
					{
						if($this->config->item('debug') == TRUE)
						    echo "Child: " . $childPersonId . " is registered for ".$currentyear . " for language ". $childLangArray[$j] . "<br/>";
					}
					else
					{
						if($this->config->item('debug') == TRUE)
						    echo "Child: " . $childPersonId . " is NOT registered for ".$currentyear . " for language ". $childLangArray[$j] . "<br/>";
						$langRegHistoryId = $this->Walk_proxy->insertLangRegistration( $childPersonId, $cmbCenterId, $langId, $childLangLevelArray[$j], $childLangSessionArray[$j], $currentyear, $dates );
						if($this->config->item('debug') == TRUE)
						    echo "Inserted Child Person: " . $langRegHistoryId . " for ".$currentyear . " for language " . $childLangArray[$j] . " level " . $childLangLevelArray[$j] . "<br/>";
					}
				}
			}
				
			if( $continueWithRegistration )
			{
				$memberRegistrationValue = new Member_registration_value();
/*				
				$memberRegistrationValue = unserialize($this->session->userdata('member_registration_value'));			
				$memberRegistrationValue = Member_registration_value::cast($memberRegistrationValue);
*/				
				$memberRegistrationValue->setPerson( $person );				
				$memberRegistrationValue->setDonation( $memberInfo->getDonation() );
				
				//$memberRegistrationValue->setWalkInfo( $memberInfo );
				
				if ($memberInfo->getLifeMember() == "yes")
					$regFee = 0.0;
				
				$memberRegistrationValue->setCMBRegistrationFee( $regFee );

				$bvFee = 0.0;
				//New fee structure for 2011-2012 for Andover				
				if (($cmbCenter == "Andover") && ($memberInfo->getLifeMember() != "yes"))
				{
					if ($numChildren == 1)
						$bvFee = 0.0;
					
					if ($numChildren > 1)
						$bvFee = 0.0;
				}
				$memberRegistrationValue->setBVRegistrationFee( $bvFee );
				
				$langFee = 0.0;
				$memberRegistrationValue->setLangRegistrationFee( $langFee );
				
				$totfee = $memberRegistrationValue->getTotalRegistrationFee();
								
				//Update all fees in cmb_reg_history
				$this->Walk_proxy->updateCMBRegHistoryFees($cmbRegHistoryId, $regFee, $bvFee, $langFee);
				
				//Add feedback to registration
				if ($cmbCenter == "Andover")
					$feedback = $this->input->post('comments');
				else
					$feedback = $this->input->post('comments1');
				
				$this->Walk_proxy->updateCMBRegHistoryComments($cmbRegHistoryId, $feedback);

				$memberRegistrationValue->setCMBRegHistoryId($cmbRegHistoryId);
				$memberRegistrationValue->setCurrentYear($currentyear);
				
				if ($totfee < 1)
				{
					//Handle case for Life member with $0 payment
					$this->Walk_proxy->confirmCMBRegistrationNoPay( $cmbRegHistoryId );
					$this->Walk_proxy->sendMemberRegistrationConfirmEmailNoPay( $memberRegistrationValue );
					redirect( base_url() . 'cmb/member_registration/success_nopay/');
				}

				//Send email confirming registration request
				try
				{
					$this->Walk_proxy->sendMemberRegistrationRequestEmail( $memberRegistrationValue, $currentyear );					
				}
				catch (Exception $e)
				{
    				echo 'Exception caught: ',  $e->getMessage(), "\n";
					redirect( base_url() . 'cmb/member_registration/registration_error/');
				}
/*				
				$this->session->unset_userdata('member_registration_value');
				$this->session->set_userdata('member_registration_value', serialize($memberRegistrationValue));
				redirect( base_url() . 'cmb/member_registration/step3/');
*/				

				//Load payment summary page
				//--------------------------------------------------			
				//Store registration data
				$paypalTempId = $this->Paypal_proxy->addTempData( serialize($memberRegistrationValue) );
				if ($paypalTempId <= 0)
				{
					redirect( base_url() . 'cmb/member_registration/registration_error/');
				}
				$this->session->set_userdata('sessionobj_temp_id', $paypalTempId);
										
				//Set temp_id for serialized registration value object in 'cmb_reg_history'
				$this->Walk_proxy->setCMBRegistrationTempId( $cmbRegHistoryId, $paypalTempId );
	
				$urlKey = $this->Walk_proxy->getMemberURLKey( $cmbRegHistoryId );
				if ($urlKey == "")
				{
					redirect( base_url() . 'cmb/member_registration/registration_error/');
				}

				$data['title'] = $currentyear.'-'.($currentyear+1).' Member Registration Summary';
				$data['view'] = 'cmb/register/member_registration_summary_view';
				$data['memberRegistrationValue'] = $memberRegistrationValue;
				$data['paypal_form'] = $this->getPayPalForm( $memberRegistrationValue->getTotalRegistrationFee(), $paypalTempId, $currentyear, $cmbRegHistoryId );
				$data['urlKey'] = $urlKey;
				
				$this->load->view( self::$REGISTRATION_TEMPLATE, $data );
				//--------------------------------------------------			
			}
			else
			{
				redirect( base_url() . 'cmb/member_registration/member_registered/');
			}
		}
		
		//Get member data for edit account
		public function edit_account( $urlKey )
		{
			$this->load->model('proxies/Walk_proxy');
			$this->load->model('proxies/Person_proxy');
			
			$is_logged_in = $this->session->userdata( 'is_logged_in' );
			if (!$is_logged_in)
			{
				redirect( base_url() . 'cmb/member/login_home/' );
			}
			
			//Get id for person who logged in
			$loginPersonId = $this->session->userdata( 'person_id' );
			if ( $loginPersonId < 1 )
			{
				redirect( base_url() . 'cmb/member/login_home/true/' );
			}

			//$seckey = $this->Person_proxy->getPrimaryPersonSecurityKey( $urlKey );			
			$seckey = $this->Person_proxy->getPersonSecurityKey( $this->session->userdata( 'person_id' ) );
			if ($seckey != $this->session->userdata( 'logged_in_key' ))
			{
				redirect( base_url() . 'cmb/member/login_home/true/' );
			}

			$curyear = $this->Walk_proxy->getCurrentYear();
			$this->load->model('values/cwr_registrant_member_homepage_value');
			$this->load->model('proxies/Cwr_registrant_member_proxy');
			$cwr_registrant_home_value = Cwr_registrant_member_homepage_value::cast($this->Cwr_registrant_member_proxy->getRegistrantMemberHomepageFromUrl_noyr( $urlKey ));
			if (!$cwr_registrant_home_value->getIsRegistered())
			{
				redirect( base_url() . 'cmb/member/homepage_error/');
			}			
						
			$this->session->unset_userdata('cwr_registrant_home_value');
			$this->session->set_userdata('cwr_registrant_home_value', serialize($cwr_registrant_home_value));

			$data['title'] = $this->Walk_proxy->getCurrentYear().'-'.($this->Walk_proxy->getCurrentYear()+1).' Edit Member Account ';
			$data['curyear'] = $this->Walk_proxy->getCurrentYear();
			$data['view'] = 'cmb/member/member_edit_view';
			$data['accountinfo'] = $cwr_registrant_home_value;
			$data['urlKey'] = $urlKey;
			$data['loggedinname'] = $this->Person_proxy->getPersonName( $loginPersonId );
			
			$this->load->view( self::$REGISTRATION_TEMPLATE, $data );
		}

		//Get member data for admin to edit account
		public function admin_edit_account( $urlKey )
		{
			$this->load->model('proxies/Walk_proxy');
			$this->load->model('proxies/Person_proxy');
			
			$is_logged_in = $this->session->userdata( 'admin_is_logged_in' );
			if (!$is_logged_in)
			{
				redirect( base_url() . 'cmb/member/login_home/' );
			}
		
			$seckey = $this->Person_proxy->getPersonSecurityKey( $this->session->userdata( 'person_id' ) );
			if ($seckey != $this->session->userdata( 'logged_in_key' ))
			{
				redirect( base_url() . 'cmb/member/login_home/true/' );
			}
			
			//Get id for person who logged in
			$loginPersonId = $this->session->userdata( 'person_id' );
			if ( $loginPersonId < 1 )
			{
				redirect( base_url() . 'cmb/member/login_home/true/' );
			}

			if (!($this->Person_proxy->isPersonGroupRole( $loginPersonId, "member", "admin" )) and (!$this->Person_proxy->isPersonGroupRole( $loginPersonId, "member", "superadmin" )))
			{
				redirect( base_url() . 'cmb/member/login_home/true/' );				
			}
/*
			//Create a login for member
			$seckey = $this->Person_proxy->getPersonSecurityKey( $this->session->userdata( 'person_id' ) );
			$this->session->set_userdata( 'member_logged_in_key', $seckey );			
*/
			$curyear = $this->Walk_proxy->getCurrentYear();
			$this->load->model('values/cwr_registrant_member_homepage_value');
			$this->load->model('proxies/Cwr_registrant_member_proxy');
			$cwr_registrant_home_value = Cwr_registrant_member_homepage_value::cast($this->Cwr_registrant_member_proxy->getRegistrantMemberHomepageFromUrl_noyr( $urlKey ));
			if (!$cwr_registrant_home_value->getIsRegistered())
			{
				redirect( base_url() . 'cmb/member/homepage_error/');
			}			
						
			$data['title'] = ' Admin Edit Member Account';
			$data['curyear'] = $this->Walk_proxy->getCurrentYear();
			$data['view'] = 'cmb/member/admin_member_edit_view';
			$data['accountinfo'] = $cwr_registrant_home_value;
			$data['urlKey'] = $urlKey;
			$data['adminUrlKey'] = $this->session->userdata( 'admin_url_key' );
			$data['loggedinname'] = $this->Person_proxy->getPersonName( $loginPersonId );
						
			$this->load->view( self::$REGISTRATION_TEMPLATE, $data );
		}

		//Member edit account process
		public function edit_account_process( $urlKey )
		{
			$this->load->model('proxies/Person_proxy');
			$this->load->model('proxies/Walk_proxy');
			$this->load->library('encrypt');
			
			$is_logged_in = $this->session->userdata( 'is_logged_in' );
			if (!$is_logged_in)
			{
				redirect( base_url() . 'cmb/member/login_home/' );
			}

			$seckey = $this->Person_proxy->getPersonSecurityKey( $this->session->userdata( 'person_id' ) );
			if ($seckey != $this->session->userdata( 'logged_in_key' ))
			{
				redirect( base_url() . 'cmb/member/login_home/true/' );
			}
			
			//Get id for person who logged in
			$loginPersonId = $this->session->userdata( 'person_id' );
			if ( $loginPersonId < 1 )
			{
				redirect( base_url() . 'cmb/member/login_home/true/' );
			}
			
			//Save To Session...
			$person = new Person_value();
			
			$cwr_registrant_home_value = unserialize($this->session->userdata('cwr_registrant_home_value'));			
			$cwr_registrant_home_value = Cwr_registrant_member_homepage_value::cast($cwr_registrant_home_value);
			
			//Primary member
			$person->setSecretQuestion( trim($this->input->post('question')) );
			$person->setSecretPhrase( trim($this->input->post('secretPhrase')) );
			$person->setEmail1( $this->input->post('primaryEmail') );
			$person->setPhone1( $this->input->post('homePhoneNumber') );
			$person->setPhone2( $this->input->post('mobilePhoneNumber') );
			$person->setOrgName( $this->input->post('orgname') );
			$person->setGender( $cwr_registrant_home_value->getGender() );
			$volInterestArray = array();
			for( $i = 1; $i <= 12; $i++ )
			{
				if( isset( $_POST['volArea' . $i] ) )
				{
					array_push( $volInterestArray, $this->input->post('volArea' . $i) );
				}
			}
			$person->setVolunteerInterests( $volInterestArray );
									
			//Spouse
			$cwr_registrant_home_value->setSpouseEmail1( $this->input->post('spouseEmail') );
			$cwr_registrant_home_value->setSpousePhone1( $this->input->post('spousePhone') );
			$cwr_registrant_home_value->setSpousePhone2( $this->input->post('spouseMobilePhone') );
			$spouseVolInterestArray = array();
			for( $i = 1; $i <= 12; $i++ )
			{
				if( isset( $_POST['spouseVolArea' . $i] ) )
				{
					array_push( $spouseVolInterestArray, $this->input->post('spouseVolArea' . $i) );
				}
			}
			
			//Household
			$person->setAddress1( $this->input->post('homeAddress1') );
			$person->setAddress2( $this->input->post('homeAddress2') );
			$person->setCity( $this->input->post('city') );
			$person->setState( $this->input->post('state') );
			$person->setZip( $this->input->post('zipCode') );			
			
			$personId = $cwr_registrant_home_value->getPersonId();
			$spousePersonId = $cwr_registrant_home_value->getSpousePersonId();
			
			if ($personId > 0)
			{
				$person->setPersonId( $personId );
				$primaryPersonId = $this->Person_proxy->updatePrimaryPerson( $person );
				
				$password = $this->input->post('password');
				if (($password != "") and ($loginPersonId > 0))
				{
					$this->Person_proxy->updatePersonPassword( $loginPersonId, $this->encrypt->encode($password) );
					$this->Walk_proxy->sendMemberChangePasswordEmail( $cwr_registrant_home_value, $this->Person_proxy->getPersonEmail($loginPersonId), $password );
					$this->session->set_userdata( 'is_logged_in', false );
				}
			}
			
			if ($spousePersonId > 0)
			{
				$spousepersonId = $this->Person_proxy->updatePerson($person, $spousePersonId, $cwr_registrant_home_value->getSpouseGender(), $cwr_registrant_home_value->getSpouseEmail1(), $cwr_registrant_home_value->getSpousePhone1(), $cwr_registrant_home_value->getSpousePhone2(), $spouseVolInterestArray);
			}
			
			if ($this->session->userdata( 'is_logged_in')) 
				redirect( base_url() . 'cmb/member/home/' . $urlKey . '/' );
			else
				redirect( base_url() . 'cmb/member/login_home/' );
		}
		
		//Admin member edit account process
		public function admin_edit_account_process( $urlKey )
		{
			$this->load->model('proxies/Person_proxy');
			$this->load->model('proxies/Walk_proxy');
			$this->load->library('encrypt');
			
			$is_logged_in = $this->session->userdata( 'admin_is_logged_in' );
			if (!$is_logged_in)
			{
				echo "Admin is not logged in";
				die;
				redirect( base_url() . 'cmb/member/login_home/' );
			}
			
			$seckey = $this->Person_proxy->getPersonSecurityKey( $this->session->userdata( 'person_id' ) );
			if ($seckey != $this->session->userdata( 'logged_in_key' ))
			{
				redirect( base_url() . 'cmb/member/login_home/true/' );
			}
			
			//Get id for person who logged in
			$loginPersonId = $this->session->userdata( 'person_id' );
			if ( $loginPersonId < 1 )
			{
				redirect( base_url() . 'cmb/member/login_home/true/' );
			}

			if (!($this->Person_proxy->isPersonGroupRole( $loginPersonId, "member", "admin" )) and (!$this->Person_proxy->isPersonGroupRole( $loginPersonId, "member", "superadmin" )))
			{
				redirect( base_url() . 'cmb/member/login_home/true/' );				
			}
/*
			$seckey = $this->Person_proxy->getPersonSecurityKey( $this->session->userdata( 'person_id' ) );
			if ($seckey != $this->session->userdata( 'member_logged_in_key' ))
			{
				echo "Security key does not match: ".$urlKey." , ".$seckey." , ".$this->session->userdata( 'member_logged_in_key' );
				die;
				redirect( base_url() . 'cmb/member/login_home/true/' );
			}
*/
			$person = new Person_value();
			
			$this->load->model('values/cwr_registrant_member_homepage_value');
			$this->load->model('proxies/Cwr_registrant_member_proxy');
			$cwr_registrant_home_value = Cwr_registrant_member_homepage_value::cast($this->Cwr_registrant_member_proxy->getRegistrantMemberHomepageFromUrl_noyr( $urlKey ));
			if (!$cwr_registrant_home_value->getIsRegistered())
			{
				redirect( base_url() . 'cmb/member/homepage_error/');
			}			

			//Primary member
			$person->setEmail1( $this->input->post('primaryEmail') );
			$person->setPhone1( $this->input->post('homePhoneNumber') );
			$person->setPhone2( $this->input->post('mobilePhoneNumber') );
			$person->setOrgName( $this->input->post('orgname') );
			$person->setGender( $cwr_registrant_home_value->getGender() );
			$volInterestArray = array();
			for( $i = 1; $i <= 12; $i++ )
			{
				if( isset( $_POST['volArea' . $i] ) )
				{
					array_push( $volInterestArray, $this->input->post('volArea' . $i) );
				}
			}
			$person->setVolunteerInterests( $volInterestArray );
									
			//Spouse
			$cwr_registrant_home_value->setSpouseEmail1( $this->input->post('spouseEmail') );
			$cwr_registrant_home_value->setSpousePhone1( $this->input->post('spousePhone') );
			$cwr_registrant_home_value->setSpousePhone2( $this->input->post('spouseMobilePhone') );
			$spouseVolInterestArray = array();
			for( $i = 1; $i <= 12; $i++ )
			{
				if( isset( $_POST['spouseVolArea' . $i] ) )
				{
					array_push( $spouseVolInterestArray, $this->input->post('spouseVolArea' . $i) );
				}
			}
			
			//Household
			$person->setAddress1( $this->input->post('homeAddress1') );
			$person->setAddress2( $this->input->post('homeAddress2') );
			$person->setCity( $this->input->post('city') );
			$person->setState( $this->input->post('state') );
			$person->setZip( $this->input->post('zipCode') );			
			
			$personId = $cwr_registrant_home_value->getPersonId();
			$spousePersonId = $cwr_registrant_home_value->getSpousePersonId();
			
			if ($personId > 0)
			{
				$person->setPersonId( $personId );
				$primaryPersonId = $this->Person_proxy->updatePrimaryPerson( $person );
			}

			if ($spousePersonId > 0)
			{
				$spousepersonId = $this->Person_proxy->updatePerson($person, $spousePersonId, $cwr_registrant_home_value->getSpouseGender(), $cwr_registrant_home_value->getSpouseEmail1(), $cwr_registrant_home_value->getSpousePhone1(), $cwr_registrant_home_value->getSpousePhone2(), $spouseVolInterestArray);
			}
		
			$adminUrlKey = $this->session->userdata( 'admin_url_key' );
			$adminSeckey = $this->session->userdata( 'admin_sec_key' );
			$this->session->set_userdata( 'logged_in_key', $adminSeckey);
			$this->session->set_userdata( 'admin_is_logged_in', true);
			
			echo "Completed: ".$cwr_registrant_home_value->getFirstName()." ".$cwr_registrant_home_value->getLastName()."</br>";
			echo "Please close page</br>";
			die;
			//redirect( base_url() . 'cmb/member_registration/admin_edit_members/' . $adminUrlKey . '/' );
		}

		//Admin edit  members
		public function admin_edit_members( $adminUrlKey )
		{
			$this->load->model('proxies/Walk_proxy');
			$this->load->model('proxies/Person_proxy');
			
			$is_logged_in = $this->session->userdata( 'admin_is_logged_in' );
			if (!$is_logged_in)
			{
				redirect( base_url() . 'cmb/member/login_home/' );
			}
			
			//Get id for person who logged in
			$loginPersonId = $this->session->userdata( 'person_id' );
			if ( $loginPersonId < 1 )
			{
				redirect( base_url() . 'cmb/member/login_home/true/' );
			}

			//$seckey = $this->Person_proxy->getPrimaryPersonSecurityKey( $urlKey );			
			$seckey = $this->Person_proxy->getPersonSecurityKey( $this->session->userdata( 'person_id' ) );
			if ($seckey != $this->session->userdata( 'logged_in_key' ))
			{
				redirect( base_url() . 'cmb/member/login_home/true/' );
			}

			$this->session->unset_userdata( 'member_logged_in_key' );
			
			$this->session->set_userdata( 'admin_url_key', $adminUrlKey );
			$this->session->set_userdata( 'admin_sec_key', $seckey );

			$curyear = $this->Walk_proxy->getCurrentYear();
			
			$unRegInfo = $this->Walk_proxy->getAllRegisteredMemberInfo();

			$data['title'] = 'Admin Edit Members ';
			$data['curyear'] = $curyear;
			$data['view'] = 'cmb/member/admin_edit_members_view';
			$data['unregInfo'] = $unRegInfo;
			$data['urlKey'] = $adminUrlKey;
			$data['loggedinname'] = $this->Person_proxy->getPersonName( $loginPersonId );
			
			$this->load->view( self::$REGISTRATION_TEMPLATE, $data );
		}

		//Various admin tasks such as check release
		public function administration( $urlKey )
		{
			$this->load->model('proxies/Walk_proxy');
			$this->load->model('proxies/Person_proxy');
			
			$is_logged_in = $this->session->userdata( 'is_logged_in' );
			if (!$is_logged_in)
			{
				redirect( base_url() . 'cmb/member/login_home/' );
			}
			
			//$seckey = $this->Person_proxy->getPrimaryPersonSecurityKey( $urlKey );			
			$seckey = $this->Person_proxy->getPersonSecurityKey( $this->session->userdata( 'person_id' ) );
			if ($seckey != $this->session->userdata( 'logged_in_key' ))
			{
				redirect( base_url() . 'cmb/member/login_home/true/' );
			}

            //Get id for person who logged in
            $loginPersonId = $this->session->userdata( 'person_id' );
            if ( $loginPersonId < 1 )
            {
                redirect( base_url() . 'cmb/member/login_home/true/' );
            }
			
			$group = $this->Person_proxy->getPersonGroup( $loginPersonId );
			$role = $this->Person_proxy->getPersonRole( $loginPersonId );
			
			$curyear = $this->Walk_proxy->getCurrentYear();

			$isAdmin = FALSE;
			if (($this->Person_proxy->isPersonGroupRole( $loginPersonId, "member", "admin" )) or ($this->Person_proxy->isPersonGroupRole( $loginPersonId, "member", "superadmin" )))
				$isAdmin = TRUE;
			
			$data['title'] = 'Administrative Tasks';
			$data['curyear'] = $curyear;
			$data['view'] = 'cmb/member/admin_tasks_view';
			$data['urlKey'] = $urlKey;
			$data['persongroup'] = $group;
			$data['personrole'] = $role;
			$data['loggedinpersonid'] = $loginPersonId;
			$data['isAdmin'] = $isAdmin;
			
			$this->load->view( self::$REGISTRATION_TEMPLATE, $data );
		}

		//Admin choose Balavihar attendance class and week
		public function admin_get_balavihar_attendance()
		{
			$this->load->model('proxies/Walk_proxy');
			$this->load->model('proxies/Person_proxy');
			
			$is_logged_in = $this->session->userdata( 'is_logged_in' );
			if (!$is_logged_in)
			{
				redirect( base_url() . 'cmb/member/login_home/' );
			}
			
			$seckey = $this->Person_proxy->getPersonSecurityKey( $this->session->userdata( 'person_id' ) );
			if ($seckey != $this->session->userdata( 'logged_in_key' ))
			{
				redirect( base_url() . 'cmb/member/login_home/true/' );
			}

			$curyear = $this->Walk_proxy->getCurrentYear();
			$currweekarr = $this->Walk_proxy->getBalaviharWeek( $curyear );
			$weekarr = $this->Walk_proxy->getBalaviharAttendanceWeek( $curyear );
/*			
			echo $currweekarr[0].",".$currweekarr[1].",".$currweekarr[2]."<br/>";
			echo "Number of weeks: ".count($weekarr)."<br/>";
			echo "Week: ".$weekarr["0"]."<br/>";
			die;
*/
			$data['title'] = 'Choose Balavihar Class and Week';
			$data['curyear'] = $curyear;
			$data['view'] = 'cmb/member/admin_balavihar_attendance_input_view';
			$data['weekarr'] = $weekarr;
			$data['curweekseq'] = $currweekarr[1]-1;
			
			$this->load->view( self::$REGISTRATION_TEMPLATE, $data );			
		}
		
		//Get class and attendance information
		public function admin_get_balavihar_attendance_process()
		{
			$this->load->model('proxies/Walk_proxy');
			$this->load->model('proxies/Person_proxy');
			
			$is_logged_in = $this->session->userdata( 'is_logged_in' );
			if (!$is_logged_in)
			{
				redirect( base_url() . 'cmb/member/login_home/' );
			}
			
			$seckey = $this->Person_proxy->getPersonSecurityKey( $this->session->userdata( 'person_id' ) );
			if ($seckey != $this->session->userdata( 'logged_in_key' ))
			{
				redirect( base_url() . 'cmb/member/login_home/true/' );
			}

			$curyear = $this->Walk_proxy->getCurrentYear();

			$centername = $this->input->post('centername');
			$session = $this->input->post('session');
			$grade = $this->input->post('grade');
			$weekseq = ($this->input->post('weekseq')+1);
			$weekdate = $this->Walk_proxy->getBalaviharWeekDate( $curyear, $weekseq);
			
			$attdsearch = array();
			array_push($attdsearch, $centername);
			array_push($attdsearch, $session);
			array_push($attdsearch, $grade);
			array_push($attdsearch, $weekseq);
			$this->session->set_userdata( 'attdsearch', $attdsearch );

			$bvattendancearr = $this->Walk_proxy->getBalaviharAttendance( $curyear, $centername, $session, $grade, $weekseq );
			
			$data['title'] = 'Update Balavihar Attendance';
			$data['curyear'] = $curyear;
			$data['view'] = 'cmb/member/admin_balavihar_attendance_update_view';
			$data['bvattendancearr'] = $bvattendancearr;
			$data['centername'] = $centername;
			$data['session'] = $session;
			$data['grade'] = $grade;
			$data['weekdate'] = $weekdate;
			
			$this->load->view( self::$REGISTRATION_TEMPLATE, $data );			
		}

		//Update class attendance information
		public function admin_update_balavihar_attendance_process()
		{
			$this->load->model('proxies/Walk_proxy');
			$this->load->model('proxies/Person_proxy');
			
			$is_logged_in = $this->session->userdata( 'is_logged_in' );
			if (!$is_logged_in)
			{
				redirect( base_url() . 'cmb/member/login_home/' );
			}
			
			$seckey = $this->Person_proxy->getPersonSecurityKey( $this->session->userdata( 'person_id' ) );
			if ($seckey != $this->session->userdata( 'logged_in_key' ))
			{
				redirect( base_url() . 'cmb/member/login_home/true/' );
			}

			$curyear = $this->Walk_proxy->getCurrentYear();

			$attdsearch = $this->session->userdata( 'attdsearch' );

			$bvattendancearr = $this->Walk_proxy->getBalaviharAttendance( $curyear, $attdsearch[0], $attdsearch[1], $attdsearch[2], $attdsearch[3] );
			foreach($bvattendancearr as $bvarec)
			{
				$bv_attend_xref_id = $bvarec[0];
				$status = $this->input->post('status'.$bv_attend_xref_id);
				//echo $bv_attend_xref_id." , ".$status."</br>";

				$this->Walk_proxy->updateBalaviharAttendance( $bv_attend_xref_id, $status );
			}

			echo "Updated Attendance for:<br/>";
			echo "Center: ".$attdsearch[0]."<br/>";
			echo "Session: ".$attdsearch[1]."<br/>";
			echo "Grade: ".$attdsearch[2]."<br/>";
			$weekdate = $this->Walk_proxy->getBalaviharWeekDate( $curyear, $attdsearch[3]);
			echo "Week: ".$weekdate."<br/>";
			die;
		}

		//Admin release checks
		public function release_check( $urlKey )
		{
			$this->load->model('proxies/Walk_proxy');
			$this->load->model('proxies/Person_proxy');
			
			$is_logged_in = $this->session->userdata( 'admin_is_logged_in' );
			if (!$is_logged_in)
			{
				redirect( base_url() . 'cmb/member/login_home/' );
			}
			
			//$seckey = $this->Person_proxy->getPrimaryPersonSecurityKey( $urlKey );			
			$seckey = $this->Person_proxy->getPersonSecurityKey( $this->session->userdata( 'person_id' ) );
			if ($seckey != $this->session->userdata( 'logged_in_key' ))
			{
				redirect( base_url() . 'cmb/member/login_home/true/' );
			}

			$curyear = $this->Walk_proxy->getCurrentYear();

			$data['title'] = 'Enter Received Check Information';
			$data['curyear'] = $curyear;
			$data['view'] = 'cmb/member/admin_release_check_view';
			$data['regInfo'] = $this->Walk_proxy->getUnpaidCheckInfo( $curyear );
			$data['urlKey'] = $urlKey;
			
			$this->load->view( self::$REGISTRATION_TEMPLATE, $data );
		}

		//Admin register members
		public function register_members( $adminUrlKey )
		{
			$this->load->model('proxies/Walk_proxy');
			$this->load->model('proxies/Person_proxy');
			
			$is_logged_in = $this->session->userdata( 'admin_is_logged_in' );
			if (!$is_logged_in)
			{
				redirect( base_url() . 'cmb/member/login_home/' );
			}
			
			//$seckey = $this->Person_proxy->getPrimaryPersonSecurityKey( $urlKey );			
			$seckey = $this->Person_proxy->getPersonSecurityKey( $this->session->userdata( 'person_id' ) );
			if ($seckey != $this->session->userdata( 'logged_in_key' ))
			{
				redirect( base_url() . 'cmb/member/login_home/true/' );
			}

			$this->session->unset_userdata( 'admin_url_key' );
			$this->session->set_userdata( 'admin_url_key', $adminUrlKey );

			$this->session->unset_userdata( 'admin_sec_key' );
			$this->session->set_userdata( 'admin_sec_key', $seckey );

			$curyear = $this->Walk_proxy->getCurrentYear();
			
			$unRegInfo = $this->Walk_proxy->getUnRegisteredMemberInfo( $curyear );

			$data['title'] = 'Admin Register Members for '.$curyear.'-'.($curyear+1);
			$data['curyear'] = $curyear;
			$data['view'] = 'cmb/member/admin_register_members_view';
			$data['unregInfo'] = $unRegInfo;
			$data['urlKey'] = $adminUrlKey;
			
			$this->load->view( self::$REGISTRATION_TEMPLATE, $data );
		}

		public function register_members_process( $urlKey )
		{
			$this->load->model('proxies/Person_proxy');
			$this->load->model('proxies/Walk_proxy');
			$this->load->library('encrypt');
			
			//Create a login for member
			$this->session->unset_userdata( 'is_logged_in' );
			$this->session->unset_userdata( 'logged_in_key' );
			$this->session->set_userdata( 'is_logged_in', true );		
			//$seckey = $this->Person_proxy->getPrimaryPersonSecurityKey( $urlKey );			
			$seckey = $this->Person_proxy->getPersonSecurityKey( $this->session->userdata( 'person_id' ) );
			$this->session->set_userdata( 'logged_in_key', $seckey );			

			//Login the user
			redirect( base_url() . 'cmb/member_registration/register_existing_member/'.$urlKey.'/');

			die;
		}
		
		public function release_check_process( $urlKey )
		{
			$this->load->model('proxies/Person_proxy');
			$this->load->model('proxies/Walk_proxy');
			$this->load->model('values/cwr_registrant_member_homepage_value');
			$this->load->model('proxies/Cwr_registrant_member_proxy');
			$this->load->library('encrypt');
			
			$is_logged_in = $this->session->userdata( 'admin_is_logged_in' );
			if (!$is_logged_in)
			{
				redirect( base_url() . 'cmb/member/login_home/' . $urlKey . '/' );
			}

			//$seckey = $this->Person_proxy->getPrimaryPersonSecurityKey( $urlKey );			
			$seckey = $this->Person_proxy->getPersonSecurityKey( $this->session->userdata( 'person_id' ) );
			if ($seckey != $this->session->userdata( 'logged_in_key' ))
			{
				redirect( base_url() . 'cmb/member/login_home/true/' );
			}

			$curyear = $this->Walk_proxy->getCurrentYear();

			//Get check info
			$RegIdArray = $this->Walk_proxy->getUnpaidCheckRegId( $curyear );
			
			for( $i = 0; $i < count($RegIdArray); $i++ )
			{
				$checknum = $this->input->post('crhid'.$RegIdArray[$i]);
				$paybypaypal = $this->input->post('paybyppid'.$RegIdArray[$i]);
				if (($checknum != "") && ($paybypaypal == "No"))
				{				
					//Update 'cmb_reg_history' for check payment
					$tmp = $this->Walk_proxy->completeCMBRegistrationCheck($RegIdArray[$i], $checknum);
					$memURLKey = $this->Walk_proxy->getMemberURLKey( $RegIdArray[$i] );
			
					$cwr_registrant_home_value = Cwr_registrant_member_homepage_value::cast($this->Cwr_registrant_member_proxy->getRegistrantMemberHomepageFromUrl( $memURLKey, $curyear));
					if (!$cwr_registrant_home_value->getIsRegistered())
					{
						redirect( base_url() . 'cmb/member/homepage_error/');
					}
						
					$this->Walk_proxy->sendMemberRegistrationCheckConfirmEmail( $cwr_registrant_home_value, $curyear, $checknum, $memURLKey );
				}
				else
				{
					if ($paybypaypal == "Yes")
					{
						//Pay by Paypal instead of by check
						//Send email link for Admin to do Paypal payment
						//---------------------------------
						
						$memURLKey = $this->Walk_proxy->getMemberURLKey( $RegIdArray[$i] );
						$cwr_registrant_home_value = Cwr_registrant_member_homepage_value::cast($this->Cwr_registrant_member_proxy->getRegistrantMemberHomepageFromUrl( $memURLKey, $curyear));
						if (!$cwr_registrant_home_value->getIsRegistered())
						{
							redirect( base_url() . 'cmb/member/homepage_error/');
						}
						
						//Change payment type to Paypal
						$this->Walk_proxy->changeCMBRegistrationPaypal( $RegIdArray[$i] );
						
						//Send email with link to make payment by Paypal
						$this->Walk_proxy->sendAdminChangePaymentPaypalEmail( $cwr_registrant_home_value, $curyear, $urlKey, $RegIdArray[$i] );
						//---------------------------------
					}
				}
			}
						
			redirect( base_url() . 'cmb/member/home/' . $urlKey . '/' );
		}
		
		//Admin capability to change payment method from check to Paypal
		public function change_payment_paypal( $urlKey, $CMBRegHistoryId )
		{
			$this->load->model('proxies/Person_proxy');
			$this->load->model('proxies/Walk_proxy');
			$this->load->model('values/cwr_registrant_member_homepage_value');
			$this->load->model('proxies/Cwr_registrant_member_proxy');
			$this->load->library('encrypt');
			
			$is_logged_in = $this->session->userdata( 'is_logged_in' );
			if (!$is_logged_in)
			{
				redirect( base_url() . 'cmb/member/login_home/' . $urlKey . '/' );
			}

			//$seckey = $this->Person_proxy->getPrimaryPersonSecurityKey( $urlKey );			
			$seckey = $this->Person_proxy->getPersonSecurityKey( $this->session->userdata( 'person_id' ) );
			if ($seckey != $this->session->userdata( 'logged_in_key' ))
			{
				redirect( base_url() . 'cmb/member/login_home/true/' );
			}

			$curyear = $this->Walk_proxy->getCurrentYear();
			
			$memURLKey = $this->Walk_proxy->getMemberURLKey( $CMBRegHistoryId );
			$cwr_registrant_home_value = Cwr_registrant_member_homepage_value::cast($this->Cwr_registrant_member_proxy->getRegistrantMemberHomepageFromUrl( $memURLKey, $curyear));
			if (!$cwr_registrant_home_value->getIsRegistered())
			{
				redirect( base_url() . 'cmb/member/homepage_error/');
			}
						
			if (!$this->Walk_proxy->isRegistrationPaid( $CMBRegHistoryId ))
			{
				//Create member registration value object
				$memberRegistrationValue = new Member_registration_value();
								
				$memberRegistrationValue->setCurrentYear($curyear);
				$memberRegistrationValue->setCMBRegHistoryId( $CMBRegHistoryId );
										
				$memberRegistrationValue->setCMBRegistrationFee( $cwr_registrant_home_value->getRegAmount() );
				$memberRegistrationValue->setBVRegistrationFee( $cwr_registrant_home_value->getBVAmount() );
				$memberRegistrationValue->setDonation( $cwr_registrant_home_value->getDonation() );
				$langFee = 0.0;
				$memberRegistrationValue->setLangRegistrationFee( $langFee );
							
				$person = new Person_value();
							
				$person->setUserName( $cwr_registrant_home_value->getUserName() );
				$person->setPassword( $cwr_registrant_home_value->getPassword() );

				$person->setFirstName( $cwr_registrant_home_value->getFirstName() );
				$person->setLastName( $cwr_registrant_home_value->getLastName() );
				$person->setSecretQuestion( $cwr_registrant_home_value->getSecretQuestion() );
				$person->setSecretPhrase( $cwr_registrant_home_value->getSecretPhrase() );
				$person->setGender( $cwr_registrant_home_value->getGender() );
				$person->setEmail1( $cwr_registrant_home_value->getEmail1() );
				$person->setPhone1( $cwr_registrant_home_value->getPhone1() );
				$person->setPhone2( $cwr_registrant_home_value->getFirstName() );
				$person->setOrgName( $cwr_registrant_home_value->getPhone1() );
				$person->setPrimaryAttendSatsang( $cwr_registrant_home_value->getSession() );
				$person->setAddress1( $cwr_registrant_home_value->getAddress1() );
				$person->setAddress2( $cwr_registrant_home_value->getAddress2() );
				$person->setCity( $cwr_registrant_home_value->getCity() );
				$person->setState( $cwr_registrant_home_value->getState() );
				$person->setZip( $cwr_registrant_home_value->getZip() );
							
				//Update specific fields based on values that were entered by user
				if($cwr_registrant_home_value->getCMBCenter() == "Andover")
				{
					$cwr_registrant_home_value->setSession( $this->input->post('primaryAttendSatsang') );
					$person->setPrimaryAttendSatsang( $cwr_registrant_home_value->getSession() );
				}
				else
				{
					//Metro-West
					$person->setPrimaryAttendSatsang( "PM" );
				}			
				
				$primaryPersonId = $cwr_registrant_home_value->getPersonId();
				$person->setPersonId($primaryPersonId);
				
				$memberRegistrationValue->setPerson( $person );
	/*			
				$this->session->unset_userdata('member_registration_value');
				$this->session->set_userdata('member_registration_value', serialize($memberRegistrationValue));
				
				redirect( base_url() . 'cmb/member_registration/step3a/');
	*/			
				//Load payment summary page
				//--------------------------------------------------			
				//Store registration data
				$paypalTempId = $this->Paypal_proxy->addTempData( serialize($memberRegistrationValue) );
				if ($paypalTempId <= 0)
				{
					//$this->session->unset_userdata('member_registration_value');
					redirect( base_url() . 'cmb/member_registration/registration_error/');
				}
				$this->session->set_userdata('sessionobj_temp_id', $paypalTempId);
										
				//Set temp_id for serialized registration value object in 'cmb_reg_history'
				$this->Walk_proxy->setCMBRegistrationTempId( $CMBRegHistoryId, $paypalTempId );
	
				$data['title'] = $curyear.'-'.($curyear+1).' Member Registration Summary';
				$data['view'] = 'cmb/register/member_registration_summary_paypalonly_view';
				$data['memberRegistrationValue'] = $memberRegistrationValue;
				$data['paypal_form'] = $this->getPayPalForm( $memberRegistrationValue->getTotalRegistrationFee(), $paypalTempId, $curyear, $CMBRegHistoryId );
				$data['urlKey'] = $urlKey;
				
				$this->load->view( self::$REGISTRATION_TEMPLATE, $data );
				//--------------------------------------------------			
			}
			else
			{
				echo "Registration for ".$cwr_registrant_home_value->getFirstName()." ".$cwr_registrant_home_value->getLastName()." is already paid";
				die;
			}
		}

		//User payment for registration after registering w/o paying
		public function member_registration_payment( $urlKey )
		{
			$this->load->model('proxies/Person_proxy');
			$this->load->model('proxies/Walk_proxy');
			$this->load->model('values/cwr_registrant_member_homepage_value');
			$this->load->model('proxies/Cwr_registrant_member_proxy');
			$this->load->library('encrypt');
			
			$is_logged_in = $this->session->userdata( 'is_logged_in' );
			if (!$is_logged_in)
			{
				redirect( base_url() . 'cmb/member/login_pay_registration/' . $urlKey . '/' );
			}

			//$seckey = $this->Person_proxy->getPrimaryPersonSecurityKey( $urlKey );			
			$seckey = $this->Person_proxy->getPersonSecurityKey( $this->session->userdata( 'person_id' ) );
			if ($seckey != $this->session->userdata( 'logged_in_key' ))
			{
				redirect( base_url() . 'cmb/member/login_pay_registration/true/' );
			}

			$curyear = $this->Walk_proxy->getCurrentYear();
			
			$CMBRegHistoryId = $this->Walk_proxy->getCMBRegHistoryIdfromURLYear( $urlKey, $curyear );
			if ($CMBRegHistoryId <= 0)
			{
				redirect( base_url() . 'cmb/member/homepage_error/');
			}
			
			$cwr_registrant_home_value = Cwr_registrant_member_homepage_value::cast($this->Cwr_registrant_member_proxy->getRegistrantMemberHomepageFromUrl( $urlKey, $curyear));
			//Make sure member is already registered
			if (!$cwr_registrant_home_value->getIsRegistered())
			{
				redirect( base_url() . 'cmb/member/homepage_error/');
			}
						
			//Make sure registration is not paid
			if (!$this->Walk_proxy->isRegistrationPaid( $CMBRegHistoryId ))
			{
				//Create member registration value object
				$memberRegistrationValue = new Member_registration_value();
							
				$memberRegistrationValue->setCurrentYear($curyear);
				$memberRegistrationValue->setCMBRegHistoryId( $CMBRegHistoryId );
									
				$memberRegistrationValue->setCMBRegistrationFee( $cwr_registrant_home_value->getRegAmount() );
				$memberRegistrationValue->setBVRegistrationFee( $cwr_registrant_home_value->getBVAmount() );
				$memberRegistrationValue->setDonation( $cwr_registrant_home_value->getDonation() );
				$langFee = 0.0;
				$memberRegistrationValue->setLangRegistrationFee( $langFee );
						
				$person = new Person_value();
						
				$person->setUserName( $cwr_registrant_home_value->getUserName() );
				$person->setPassword( $cwr_registrant_home_value->getPassword() );

				$person->setFirstName( $cwr_registrant_home_value->getFirstName() );
				$person->setLastName( $cwr_registrant_home_value->getLastName() );
				$person->setSecretQuestion( $cwr_registrant_home_value->getSecretQuestion() );
				$person->setSecretPhrase( $cwr_registrant_home_value->getSecretPhrase() );
				$person->setGender( $cwr_registrant_home_value->getGender() );
				$person->setEmail1( $cwr_registrant_home_value->getEmail1() );
				$person->setPhone1( $cwr_registrant_home_value->getPhone1() );
				$person->setPhone2( $cwr_registrant_home_value->getFirstName() );
				$person->setOrgName( $cwr_registrant_home_value->getPhone1() );
				$person->setPrimaryAttendSatsang( $cwr_registrant_home_value->getSession() );
				$person->setAddress1( $cwr_registrant_home_value->getAddress1() );
				$person->setAddress2( $cwr_registrant_home_value->getAddress2() );
				$person->setCity( $cwr_registrant_home_value->getCity() );
				$person->setState( $cwr_registrant_home_value->getState() );
				$person->setZip( $cwr_registrant_home_value->getZip() );
						
				//Update specific fields based on values that were entered by user
				if($cwr_registrant_home_value->getCMBCenter() == "Andover")
				{
					$cwr_registrant_home_value->setSession( $this->input->post('primaryAttendSatsang') );
					$person->setPrimaryAttendSatsang( $cwr_registrant_home_value->getSession() );
				}
				else
				{
					//Metro-West
					$person->setPrimaryAttendSatsang( "PM" );
				}			
			
				$primaryPersonId = $cwr_registrant_home_value->getPersonId();
				$person->setPersonId($primaryPersonId);
			
				$memberRegistrationValue->setPerson( $person );
/*			
				$this->session->unset_userdata('member_registration_value');
				$this->session->set_userdata('member_registration_value', serialize($memberRegistrationValue));
			
				redirect( base_url() . 'cmb/member_registration/step3b/');
*/				
				//Get object id from existing registration
				$paypalTempId = $this->Walk_proxy->getTempIDCMBRegistration( $CMBRegHistoryId );			
				if ($paypalTempId <= 0)
				{
					$this->session->unset_userdata('member_registration_value');
					redirect( base_url() . 'cmb/member_registration/registration_error/');
				}
				$this->session->unset_userdata('sessionobj_temp_id');
				$this->session->set_userdata('sessionobj_temp_id', $paypalTempId);
				
				$urlKey = $this->Walk_proxy->getMemberURLKey( $CMBRegHistoryId );
				if ($urlKey == "")
				{
					redirect( base_url() . 'cmb/member_registration/registration_error/');
				}
				
				$data['title'] = $curyear.'-'.($curyear+1).' Member Registration Summary';
				$data['view'] = 'cmb/register/member_registration_summary_view';
				$data['memberRegistrationValue'] = $memberRegistrationValue;
				$data['paypal_form'] = $this->getPayPalForm( $memberRegistrationValue->getTotalRegistrationFee(), $paypalTempId, $curyear, $CMBRegHistoryId );
				$data['urlKey'] = $urlKey;
				
				$this->load->view( self::$REGISTRATION_TEMPLATE, $data );
			}
			else
			{
				redirect( base_url() . 'cmb/member_registration/registration_paid/');
			}
		}

		//Registration of existing member
		public function register_existing_member( $urlKey )
		{
			$this->load->model('proxies/Walk_proxy');
			$this->load->model('proxies/Person_proxy');
			$this->load->model('proxies/Paypal_proxy');
						
			$is_logged_in = $this->session->userdata( 'is_logged_in' );
			if (!$is_logged_in)
			{
				redirect( base_url() . 'cmb/member/login_register/' . $urlKey . '/' );
			}
						
			//$seckey = $this->Person_proxy->getPrimaryPersonSecurityKey( $urlKey );			
			$seckey = $this->Person_proxy->getPersonSecurityKey( $this->session->userdata( 'person_id' ) );
			if ($seckey != $this->session->userdata( 'logged_in_key' ))
			{
				redirect( base_url() . 'cmb/member/login_register/true/' );
			}

			//Get registration data from database using 'urlKey'
			$curyear = $this->Walk_proxy->getCurrentYear();
			$this->load->model('values/cwr_registrant_member_homepage_value');
			$this->load->model('proxies/Cwr_registrant_member_proxy');
			$cwr_registrant_home_value = Cwr_registrant_member_homepage_value::cast($this->Cwr_registrant_member_proxy->getRegistrantMemberHomepageFromUrl( $urlKey, $curyear ));
			
            $data['title'] = $this->Walk_proxy->getCurrentYear().'-'.($curyear+1).' Existing Member Registration ';
            $data['curyear'] = $this->Walk_proxy->getCurrentYear();

            if ($this->Walk_proxy->isRegistrationOpen())
            {
                //Check if already registered
                $CMBRegHistoryId = $this->Walk_proxy->getCMBRegHistoryIdfromURLYear( $urlKey, $curyear );
                if ($CMBRegHistoryId > 0)
                {
                    //Don't delete pending or completed registrations
                    if ($this->Walk_proxy->getCMBRegistrationPaymentStatus($CMBRegHistoryId) > 0)
                    //if ($this->Walk_proxy->isRegisteredByCheck($CMBRegHistoryId))
                    {
                        redirect( base_url() . 'cmb/member_registration/member_registered/');
                    }
    
                    //Check if registration is paid
                    if ($this->Walk_proxy->isRegistrationPaid($CMBRegHistoryId))
                    {
                        redirect( base_url() . 'cmb/member_registration/member_registered/');
                    }
                    else
                    {
                        //If registration is not paid remove registration info for current year
                        //Remove any associated entry in 'paypal_temp'
                        $paypalTempId = $this->Walk_proxy->getTempIDCMBRegistration( $CMBRegHistoryId );                
                        if ($paypalTempId > 0)
                            $this->Walk_proxy->deleteRegTempObj( $paypalTempId );
                        
                        //Remove entry in 'cmb_reg_history
                        $this->Walk_proxy->deleteCMBRegistration( $CMBRegHistoryId );
                        
                        //Remove entries in 'bv_reg_history'
                        $childPersonIdArray = $cwr_registrant_home_value->getChildPersonIdArray();
                        $this->Walk_proxy->deleteBVRegistration( $childPersonIdArray, $curyear );
                        
                        //Remove entries in 'lang_reg_history'
                        $childLangArray = $cwr_registrant_home_value->getChildLang();
                        $this->Walk_proxy->deleteLangRegistration( $childPersonIdArray, $childLangArray, $curyear );
                    }           
                }
    /*                  
                if ($cwr_registrant_home_value->getIsRegistered())
                {
                    redirect( base_url() . 'cmb/member_registration/member_registered/');
                }           
    */
                //Get registration data from previous year
                $cwr_registrant_home_value = Cwr_registrant_member_homepage_value::cast($this->Cwr_registrant_member_proxy->getRegistrantMemberHomepageFromUrl_noyr( $urlKey ));
                
                //Save registration data to session
                //$this->session->set_userdata('cwr_registrant_home_value', serialize($cwr_registrant_home_value));
                
                $data['accountinfo'] = $cwr_registrant_home_value;
                $data['urlKey'] = $urlKey;
                $data['regAmount'] = $this->Walk_proxy->getCurrentRegAmount($cwr_registrant_home_value->getCMBCenter());
                $data['view'] = 'cmb/register/register_existing_person_view';
            }
            else
            {
                $datesBV = $this->Walk_proxy->getCurrentBVEventDates($this->Walk_proxy->getCurrentYear());
                $data['open_date'] = $datesBV[2];               
                $data['view'] = 'cmb/register/registration_closed_view';
            }
			
			
			$this->load->view( self::$REGISTRATION_TEMPLATE, $data );
		}
		
        //Registration of existing teacher member
        public function register_existing_teacher_member( $urlKey )
        {
            $this->load->model('proxies/Walk_proxy');
            $this->load->model('proxies/Person_proxy');
            $this->load->model('proxies/Paypal_proxy');
                        
            $is_logged_in = $this->session->userdata( 'is_logged_in' );
            if (!$is_logged_in)
            {
                redirect( base_url() . 'cmb/member/login_register/' . $urlKey . '/' );
            }
                        
            //$seckey = $this->Person_proxy->getPrimaryPersonSecurityKey( $urlKey );            
            $seckey = $this->Person_proxy->getPersonSecurityKey( $this->session->userdata( 'person_id' ) );
            if ($seckey != $this->session->userdata( 'logged_in_key' ))
            {
                redirect( base_url() . 'cmb/member/login_register/true/' );
            }

            //Get registration data from database using 'urlKey'
            $curyear = $this->Walk_proxy->getCurrentYear();
            $this->load->model('values/cwr_registrant_member_homepage_value');
            $this->load->model('proxies/Cwr_registrant_member_proxy');
            $cwr_registrant_home_value = Cwr_registrant_member_homepage_value::cast($this->Cwr_registrant_member_proxy->getRegistrantMemberHomepageFromUrl( $urlKey, $curyear ));
            
            $data['title'] = $this->Walk_proxy->getCurrentYear().'-'.($curyear+1).' Existing Member Registration ';
            $data['curyear'] = $this->Walk_proxy->getCurrentYear();

            if ($this->Walk_proxy->isTeacherRegistrationOpen())
            {
                //Check if already registered
                $CMBRegHistoryId = $this->Walk_proxy->getCMBRegHistoryIdfromURLYear( $urlKey, $curyear );
                if ($CMBRegHistoryId > 0)
                {
                    //Don't delete pending or completed registrations
                    if ($this->Walk_proxy->getCMBRegistrationPaymentStatus($CMBRegHistoryId) > 0)
                    //if ($this->Walk_proxy->isRegisteredByCheck($CMBRegHistoryId))
                    {
                        redirect( base_url() . 'cmb/member_registration/member_registered/');
                    }
    
                    //Check if registration is paid
                    if ($this->Walk_proxy->isRegistrationPaid($CMBRegHistoryId))
                    {
                        redirect( base_url() . 'cmb/member_registration/member_registered/');
                    }
                    else
                    {
                        //If registration is not paid remove registration info for current year
                        //Remove any associated entry in 'paypal_temp'
                        $paypalTempId = $this->Walk_proxy->getTempIDCMBRegistration( $CMBRegHistoryId );                
                        if ($paypalTempId > 0)
                            $this->Walk_proxy->deleteRegTempObj( $paypalTempId );
                        
                        //Remove entry in 'cmb_reg_history
                        $this->Walk_proxy->deleteCMBRegistration( $CMBRegHistoryId );
                        
                        //Remove entries in 'bv_reg_history'
                        $childPersonIdArray = $cwr_registrant_home_value->getChildPersonIdArray();
                        $this->Walk_proxy->deleteBVRegistration( $childPersonIdArray, $curyear );
                        
                        //Remove entries in 'lang_reg_history'
                        $childLangArray = $cwr_registrant_home_value->getChildLang();
                        $this->Walk_proxy->deleteLangRegistration( $childPersonIdArray, $childLangArray, $curyear );
                    }           
                }
    /*                  
                if ($cwr_registrant_home_value->getIsRegistered())
                {
                    redirect( base_url() . 'cmb/member_registration/member_registered/');
                }           
    */
                //Get registration data from previous year
                $cwr_registrant_home_value = Cwr_registrant_member_homepage_value::cast($this->Cwr_registrant_member_proxy->getRegistrantMemberHomepageFromUrl_noyr( $urlKey ));
                
                //Save registration data to session
                //$this->session->set_userdata('cwr_registrant_home_value', serialize($cwr_registrant_home_value));
                
                $data['accountinfo'] = $cwr_registrant_home_value;
                $data['urlKey'] = $urlKey;
                $data['regAmount'] = $this->Walk_proxy->getCurrentRegAmount($cwr_registrant_home_value->getCMBCenter());
                $data['view'] = 'cmb/register/register_existing_person_view';
            }
            else
            {
                $datesBV = $this->Walk_proxy->getCurrentBVEventDates($this->Walk_proxy->getCurrentYear());
                $data['open_date'] = $datesBV[2];               
                $data['view'] = 'cmb/register/registration_closed_view';
            }
            
            
            $this->load->view( self::$REGISTRATION_TEMPLATE, $data );
        }
        
		public function register_existing_member_process( $urlKey )
		{
			$this->load->model('proxies/Person_proxy');
			$this->load->model('proxies/Walk_proxy');
			$this->load->model('proxies/Paypal_proxy');
			$this->load->library('encrypt');
			
			$is_logged_in = $this->session->userdata( 'is_logged_in' );
			if (!$is_logged_in)
			{
				redirect( base_url() . 'cmb/member/login_register/' );
			}

			//$seckey = $this->Person_proxy->getPrimaryPersonSecurityKey( $urlKey );			
			$seckey = $this->Person_proxy->getPersonSecurityKey( $this->session->userdata( 'person_id' ) );
			if ($seckey != $this->session->userdata( 'logged_in_key' ))
			{
				redirect( base_url() . 'cmb/member/login_register/true/' );
			}

			$currentyear = $this->Walk_proxy->getCurrentYear();;
			$this->load->model('values/cwr_registrant_member_homepage_value');
			$this->load->model('proxies/Cwr_registrant_member_proxy');

			//Create Registration Value In Session
			$memberRegistrationValue = new Member_registration_value();				
			$memberRegistrationValue->setCurrentYear($currentyear);
			
			//Remove from session
			$this->session->unset_userdata('cwr_registrant_home_value');
			
			//Check if already registered
			$CMBRegHistoryId = $this->Walk_proxy->getCMBRegHistoryIdfromURLYear( $urlKey, $currentyear );
			if ($CMBRegHistoryId > 0)
			{
				//Check if registration is paid or pending
				if ($this->Walk_proxy->getCMBRegistrationPaymentStatus($CMBRegHistoryId) > 0)
				//if (($this->Walk_proxy->isRegistrationPaid($CMBRegHistoryId)) or ($this->Walk_proxy->isRegisteredByCheck($CMBRegHistoryId)))
				{
					redirect( base_url() . 'cmb/member_registration/member_registered/');
				}
				else
				{
					//If registration is not paid remove registration info for current year
					$cwr_registrant_home_value = Cwr_registrant_member_homepage_value::cast($this->Cwr_registrant_member_proxy->getRegistrantMemberHomepageFromUrl( $urlKey, $currentyear ));

					//Remove any associated entry in 'paypal_temp'
					$paypalTempId = $this->Walk_proxy->getTempIDCMBRegistration( $CMBRegHistoryId );				
					if ($paypalTempId > 0)
						$this->Walk_proxy->deleteRegTempObj( $paypalTempId );
					
					//Remove entry in 'cmb_reg_history
					$this->Walk_proxy->deleteCMBRegistration( $CMBRegHistoryId );
					
					//Remove entries in 'bv_reg_history'
					$childPersonIdArray = $cwr_registrant_home_value->getChildPersonIdArray();
					$this->Walk_proxy->deleteBVRegistration( $childPersonIdArray, $currentyear );
					
					//Remove entries in 'lang_reg_history'
					$childLangArray = $cwr_registrant_home_value->getChildLang();
					$this->Walk_proxy->deleteLangRegistration( $childPersonIdArray, $childLangArray, $currentyear );
					
					//redirect( base_url() . 'cmb/member_registration/incomplete_registration/');
				}			
			}
					
			//Get registration data from previous year
			$cwr_registrant_home_value = Cwr_registrant_member_homepage_value::cast($this->Cwr_registrant_member_proxy->getRegistrantMemberHomepageFromUrl_noyr( $urlKey ));

			$person = new Person_value();
			$memberInfo = new Member_info_value();
			$regFee = $this->Walk_proxy->getCurrentRegAmount( $cwr_registrant_home_value->getCMBCenter() );
			$memberInfo->setCMBCenter($cwr_registrant_home_value->getCMBCenter());
			$memberInfo->setRegistrationFee( $regFee );

			$person->setUserName( $cwr_registrant_home_value->getUserName() );
			$person->setPassword( $cwr_registrant_home_value->getPassword() );

			$person->setFirstName( $cwr_registrant_home_value->getFirstName() );
			$person->setLastName( $cwr_registrant_home_value->getLastName() );
			$displayName = $person->getFirstName() .' '. $person->getLastName();
			$memberInfo->setDisplayName( $displayName );
			$person->setSecretQuestion( $cwr_registrant_home_value->getSecretQuestion() );
			$person->setSecretPhrase( $cwr_registrant_home_value->getSecretPhrase() );
			$person->setGender( $cwr_registrant_home_value->getGender() );
			$person->setEmail1( $cwr_registrant_home_value->getEmail1() );
			$person->setPhone1( $cwr_registrant_home_value->getPhone1() );
			$person->setPhone2( $cwr_registrant_home_value->getFirstName() );
			$person->setOrgName( $cwr_registrant_home_value->getPhone1() );
			$person->setPrimaryAttendSatsang( $cwr_registrant_home_value->getSession() );
			if ($cwr_registrant_home_value->getSpouseFirstName() != "")
			{
				$memberInfo->setSpouseAttendSatsang( $cwr_registrant_home_value->getSpouseSession() );				
			}
			$person->setAddress1( $cwr_registrant_home_value->getAddress1() );
			$person->setAddress2( $cwr_registrant_home_value->getAddress2() );
			$person->setCity( $cwr_registrant_home_value->getCity() );
			$person->setState( $cwr_registrant_home_value->getState() );
			$person->setZip( $cwr_registrant_home_value->getZip() );
			
			if ($cwr_registrant_home_value->getMemberType() == "Life")
				$memberInfo->setLifeMember( "yes" );
			else
				$memberInfo->setLifeMember( "no" );
			
			//Update specific fields based on values that were entered by user
			if($cwr_registrant_home_value->getCMBCenter() == "Andover")
			{
				//$cwr_registrant_home_value->setSession( $this->input->post('primaryAttendSatsang') );
				$person->setPrimaryAttendSatsang( $cwr_registrant_home_value->getSession() );

				if ($cwr_registrant_home_value->getSpouseFirstName() != "")
				{
					//$cwr_registrant_home_value->setSpouseSession( $this->input->post('primaryAttendSatsang') );
					$memberInfo->setSpouseAttendSatsang( $cwr_registrant_home_value->getSpouseSession() );
				}
				else
					$memberInfo->setSpouseAttendSatsang( "" );
			}
			else
			{
				//Metro-West
				$person->setPrimaryAttendSatsang( "PM" );

				if ($cwr_registrant_home_value->getSpouseFirstName() != "")
				{
					$memberInfo->setSpouseAttendSatsang( "PM" );
				}
				else
					$memberInfo->setSpouseAttendSatsang( "" );			
			}
						
			//Handle existing children for Balavihar
			//------------------------
          	$numChildren = count($cwr_registrant_home_value->getChildInfo());
			$childInfoArray = array(); //Stores attributes per child
			$childInfoArray_old = $cwr_registrant_home_value->getChildInfo();
			$childPersonIdArray = array();
			$childPersonIdArray_old = $cwr_registrant_home_value->getChildPersonIdArray();
			$cidxoff = 0;
			if($numChildren > 0)
			{			
				$i = 0;
				for( $k = 0; $k < $numChildren; $k++ )
				{			
					$childInfo = array();
					$childInfo_old = $childInfoArray_old[$k];
					
					//Only get children that are enabled
					if ($childInfo_old[7] == "1")
					{
						//Check if request to remove child
						if ($this->input->post('childRemove'.($i+1)) == "No")
						{
							$childInfo[0] = $childInfo_old[0]; //First Name
							$childInfo[1] = $childInfo_old[1]; //Last Name
							$childInfo[2] = $childInfo_old[2]; //Gender
 														
							
							//$childInfo[3] = $childInfo_old[3]; //Email1
							$childInfo[3] = $this->input->post('existChildEmail'.($i+1));
							$this->Person_proxy->updateChildPersonEmail1( $childPersonIdArray_old[$k], $childInfo[3] );
							
							//$childInfo[4] = $childInfo_old[4]; //DOB
							$childInfo[4] = $this->input->post('existChildDOB'.($i+1));
							//Update child DOB in person table
							$this->Person_proxy->updateChildPersonDOB( $childPersonIdArray_old[$k], $childInfo[4] );
														
							$childInfo[5] = $this->input->post('childGrade'.($i+1));		
							if ($cwr_registrant_home_value->getCMBCenter() == "Andover")
							{
 								$childInfo[6] = $this->input->post('childSession'.($i+1));
							}
							else
							{
								//For Metro-West
								$childInfo[6] = "PM";
							}
							$childInfo[7] = $childInfo_old[7];		
				
							array_push($childPersonIdArray, $childPersonIdArray_old[$k]);
							array_push($childInfoArray, $childInfo);										
					
							/* echo $childInfo[0];
							echo $this->input->post('childGrade'.($i+1));
							echo $this->input->post('childSession'.($i+1));
							echo $this->input->post('childLang'.($i+1));
							echo $this->input->post('childLangLevel'.($i+1)); */
						}
						
						$i++;
					}
				}
				
				$cidxoff = $i;
				$cwr_registrant_home_value->setChildInfo($childInfoArray);
			} //if($numChildren > 0)
			
			//Handle existing children for language class
			//------------------------
			$childLangArray = array(); //Stores language class per child
			$childLangLevelArray = array(); //Stores language class level per child
			$childLangSessionArray = array(); //Stores language session per child
			$childLangPersonIdArray = array();
 			if($numChildren > 0)
			{			
				$i = 0;
				for( $k = 0; $k < $numChildren; $k++ )
				{								
					$childInfo_old = $childInfoArray_old[$k];

					//Only get children that are enabled
					if ($childInfo_old[7] == "1")
					{
						//Check if request to remove child
						if ($this->input->post('childRemove'.($i+1)) == "No")
						{
							//Only get children that have selected a language
							if ($this->input->post('childLang'.($i+1)) != "None")
							{				
								array_push($childLangPersonIdArray, $childPersonIdArray_old[$k]);
                                if ($cwr_registrant_home_value->getCMBCenter() == "Andover")
                                {                                
                                    array_push($childLangArray, $this->input->post('childLang'.($i+1)));
                                    array_push($childLangLevelArray, $this->input->post('childLangLevel'.($i+1)));
                                    array_push($childLangSessionArray, $this->input->post('childLangSession'.($i+1)));
                                }
                                else
                                {
                                    array_push($childLangArray, $this->input->post('childLangmw'.($i+1)));
                                    array_push($childLangLevelArray, $this->input->post('childLangLevelmw'.($i+1)));
                                    array_push($childLangSessionArray, "PM");
                                }
					
								$i ++;
							}
						}
					}
				}
				
				$cwr_registrant_home_value->setChildLang($childLangArray);
				$cwr_registrant_home_value->setChildLangLevel($childLangLevelArray);
			} //if($numChildren > 0)

			$primaryPersonId = $cwr_registrant_home_value->getPersonId();
			$person->setPersonId($primaryPersonId);
			$householdId = $this->Person_proxy->getHouseholdID( $primaryPersonId );
			$cmbCenterId = $this->Walk_proxy->getCMBCenterId($memberInfo->getCMBCenter());
						
			//$donationopt = $this->input->post('donationopt');
			//if ($donationopt != "yes")
				//$donationamount = "0.0";
			//else
				
			$donationamount = $this->input->post('donationamount');
			if (is_numeric($donationamount))
			{
				if ($donationamount < 0)
					$donationamount = 0;
			}
			else
				$donationamount = 0;
			
			$memberRegistrationValue->setDonation($donationamount);
			$memberInfo->setDonation($donationamount);
							
			//Register member for current year
			$cmbRegHistoryId = $this->Walk_proxy->insertCMBRegistration( $householdId, $cmbCenterId, $regFee, $currentyear, $person->getPrimaryAttendSatsang(), $memberInfo );
			if($this->config->item('debug') == TRUE)
				echo "Registered CMB: " . $cmbRegHistoryId . "<br/>";
			$memberInfo->setCMBRegHistoryId($cmbRegHistoryId);
			$memberRegistrationValue->setCMBRegHistoryId($cmbRegHistoryId);
						
			//Register Children for Balavihar
			$datesBV = $this->Walk_proxy->getCurrentBVEventDates($currentyear);
			
			$numEnabledChildren = count($childInfoArray);
			for( $i = 0; $i < $numEnabledChildren; $i++ )
			{
				$childPersonId = $childPersonIdArray[$i];
				$childInfo = $childInfoArray[$i];
				
				$bvRegHistoryId = $this->Walk_proxy->insertBVRegistration( $childPersonId, $cmbCenterId, $currentyear, $datesBV, $childInfo );
				if($this->config->item('debug') == TRUE)
					echo "Registered Child " .$i.": " . $bvRegHistoryId . "<br/>";
			}
			
			//Register Children for language classes
			$datesLang = $this->Walk_proxy->getCurrentLangEventDates();
			
			$numEnabledLangChildren = count($childLangArray);
			for( $i = 0; $i < $numEnabledLangChildren; $i++ )
			{
				$childPersonId = $childLangPersonIdArray[$i];
				
				if ($childLangArray[$i] != "None")
				{
					$langId = $this->Walk_proxy->getLangId($childLangArray[$i]);
				
                    if ($cwr_registrant_home_value->getCMBCenter() == "Andover")
                    {                                
				 	      $langRegHistoryId = $this->Walk_proxy->insertLangRegistration( $childPersonId, $cmbCenterId, $langId, $childLangLevelArray[$i], $childLangSessionArray[$i], $currentyear, $datesLang );
                    }
                    else
                    {
                          $langRegHistoryId = $this->Walk_proxy->insertLangRegistration( $childPersonId, $cmbCenterId, $langId, $childLangLevelArray[$i], "PM", $currentyear, $datesLang );                        
                    }
					if($this->config->item('debug') == TRUE)
						echo "Registered Child " .$i.", Lang:" . $langId.", :".$langRegHistoryId . "<br/>";
				}
			}
			//------------------------

			//Handle any additional children
			if ($this->input->post('numChildren') != "")
				$numAddChildren = $this->input->post('numChildren');
			else
				$numAddChildren = 0;
			
			//------------------------
			if ($numAddChildren > 0)
			{
				for( $i = 0; $i < $numAddChildren; $i++ )
				{
					$childInfoArray = array();
					
					array_push($childInfoArray, $this->input->post('childFN'.($cidxoff+$i+1)));
					array_push($childInfoArray, $this->input->post('childLN'.($cidxoff+$i+1)));
					array_push($childInfoArray, $this->input->post('childG'.($cidxoff+$i+1)));
					array_push($childInfoArray, $this->input->post('childEM'.($cidxoff+$i+1)));
					array_push($childInfoArray, $this->input->post('childDOB'.($cidxoff+$i+1)));
					array_push($childInfoArray, $this->input->post('childGrade'.($cidxoff+$i+1)));
					if ($cwr_registrant_home_value->getCMBCenter() == "Andover")
					{
						$childSess = $this->input->post('childSession'.($cidxoff+$i+1));
					}
					else
						$childSess = "PM";
					array_push($childInfoArray, $childSess);
										
					//Insert child into 'person' table
					$childPersonId = $this->Person_proxy->insertChildPerson( $person, $childInfoArray[0], $childInfoArray[1], $childInfoArray[2], $childInfoArray[3], $childInfoArray[4]);
					
					//Insert child into household
					$temphhId = $this->Person_proxy->insertChildHousehold( $childPersonId, $householdId );
					
					//Register child for Balavihar
					$bvRegHistoryId = $this->Walk_proxy->insertBVRegistration( $childPersonId, $cmbCenterId, $currentyear, $datesBV, $childInfoArray );
					
					//Register child for language class
					if ($this->input->post('childLang'.($cidxoff+$i+1)) != "None")
					{
                        if ($cwr_registrant_home_value->getCMBCenter() == "Andover")
                        {                                
                            $langId = $this->Walk_proxy->getLangId($this->input->post('childLang'.($cidxoff+$i+1)));
                            $childLangLevel = $this->input->post('childLangLevel'.($cidxoff+$i+1));
                            $childLangSession = $this->input->post('childLangSession'.($cidxoff+$i+1));
                        }
                        else
                        {
                            $langId = $this->Walk_proxy->getLangId($this->input->post('childLangmw'.($cidxoff+$i+1)));
                            $childLangLevel = $this->input->post('childLangLevelmw'.($cidxoff+$i+1));
                            $childLangSession = "PM";                        
                        }
						
						$langRegHistoryId = $this->Walk_proxy->insertLangRegistration( $childPersonId, $cmbCenterId, $langId, $childLangLevel, $childLangSession, $currentyear, $datesLang );
					}
					
					//echo "Child FN: " .$childInfoArray[0]. "<br/>";
					//echo "Child LN: " .$childInfoArray[1]. "<br/>";
					//echo "Child Gender: " .$childInfoArray[2]. "<br/>";
					//echo "Child Email: " .$childInfoArray[3]. "<br/>";
					//echo "Child DOB: " .$childInfoArray[4]. "<br/>";
					//echo "Child Grade: " .$childInfoArray[5]. "<br/>";
				} //for( $i = 0; $i < $numAddChildren; $i++ )
			} //if ($numAddChildren > 0)
			//------------------------

			$memberRegistrationValue->setPerson( $person );
				
			if ($memberInfo->getLifeMember() == "yes")
				$regFee = 0.0;
				
			$memberRegistrationValue->setCMBRegistrationFee( $regFee );

			$bvFee = 0.0;
			$numTotalChildren = $numEnabledChildren + $numAddChildren;
			//New fee structure for 2011-2012 for Andover				
			if (($cmbCenterId == 2) && ($memberInfo->getLifeMember() != "yes"))
			{						
				if ($numTotalChildren == 1)
					$bvFee = 0.0;
					
				if ($numTotalChildren > 1)
					$bvFee = 0.0;
			}
			$memberRegistrationValue->setBVRegistrationFee( $bvFee );
			
			$langFee = 0.0;
			$memberRegistrationValue->setLangRegistrationFee( $langFee );
						
			//Update all fees in cmb_reg_history
			$this->Walk_proxy->updateCMBRegHistoryFees($cmbRegHistoryId, $regFee, $bvFee, $langFee);
			
			//Add feedback to registration
			$feedback = $this->input->post('comments');
			$this->Walk_proxy->updateCMBRegHistoryComments($cmbRegHistoryId, $feedback);

			$totfee = $memberRegistrationValue->getTotalRegistrationFee();
				
			if ($totfee < 1)
			{
				//Handle case for Life member with $0 payment
				$this->Walk_proxy->confirmCMBRegistrationNoPay( $cmbRegHistoryId );
				$this->Walk_proxy->sendMemberRegistrationConfirmEmailNoPay( $memberRegistrationValue );
				redirect( base_url() . 'cmb/member_registration/success_nopay/');
			}

			//Send email confirming registration request
			$this->Walk_proxy->sendMemberRegistrationRequestEmail( $memberRegistrationValue, $currentyear );
			
			//$this->session->unset_userdata('member_registration_value');
/*			
			$this->session->set_userdata('member_registration_value', serialize($memberRegistrationValue));		
			redirect( base_url() . 'cmb/member_registration/step3/');
*/				
			//Load payment summary page
			//--------------------------------------------------			
			//Store registration data
			$paypalTempId = $this->Paypal_proxy->addTempData( serialize($memberRegistrationValue) );
			if ($paypalTempId <= 0)
			{
				//$this->session->unset_userdata('member_registration_value');
				redirect( base_url() . 'cmb/member_registration/registration_error/');
			}
			$this->session->set_userdata('sessionobj_temp_id', $paypalTempId);
									
			//Set temp_id for serialized registration value object in 'cmb_reg_history'
			$this->Walk_proxy->setCMBRegistrationTempId( $cmbRegHistoryId, $paypalTempId );

			$data['title'] = $currentyear.'-'.($currentyear+1).' Member Registration Summary';
			$data['view'] = 'cmb/register/member_registration_summary_view';
			$data['memberRegistrationValue'] = $memberRegistrationValue;
			$data['paypal_form'] = $this->getPayPalForm( $memberRegistrationValue->getTotalRegistrationFee(), $paypalTempId, $currentyear, $cmbRegHistoryId );
			$data['urlKey'] = $urlKey;
			
			$this->load->view( self::$REGISTRATION_TEMPLATE, $data );
			//--------------------------------------------------			
		}

		//Ask for payment for new registration
		public function step3()
		{
			$this->load->model('proxies/Paypal_proxy');
			$this->load->model('proxies/Walk_proxy');
			
			$paypalTempId = $this->Paypal_proxy->addTempData( $this->session->userdata('member_registration_value') );
			if ($paypalTempId <= 0)
			{
				$this->session->unset_userdata('member_registration_value');
				redirect( base_url() . 'cmb/member_registration/registration_error/');
			}
			$this->session->unset_userdata('sessionobj_temp_id');
			$this->session->set_userdata('sessionobj_temp_id', $paypalTempId);
						
			$memberRegistrationValue = unserialize($this->session->userdata('member_registration_value'));
			$memberRegistrationValue = Member_registration_value::cast($memberRegistrationValue);

			$cmbRegHistoryId = $memberRegistrationValue->getCMBRegHistoryId();
			$urlKey = $this->Walk_proxy->getMemberURLKey( $cmbRegHistoryId );
			if ($urlKey == "")
			{
				redirect( base_url() . 'cmb/member_registration/registration_error/');
			}
			
			//Set temp_id for serialized registration value object in 'cmb_reg_history'
			$this->Walk_proxy->setCMBRegistrationTempId( $cmbRegHistoryId, $paypalTempId );

			$data['title'] = $this->Walk_proxy->getCurrentYear().'-'.($this->Walk_proxy->getCurrentYear()+1).' Member Registration Summary';
			$data['view'] = 'cmb/register/member_registration_summary_view';
			$data['memberRegistrationValue'] = $memberRegistrationValue;
			$data['paypal_form'] = $this->getPayPalForm( $memberRegistrationValue->getTotalRegistrationFee(), $paypalTempId, $this->Walk_proxy->getCurrentYear(), $memberRegistrationValue->getCMBRegHistoryId() );
			$data['urlKey'] = $urlKey;
			
			$this->load->view( self::$REGISTRATION_TEMPLATE, $data );
		}
				
		//Ask for payment to change registration payment from 'check' to 'Paypal'
		public function step3a()
		{
			$this->load->model('proxies/Paypal_proxy');
			$this->load->model('proxies/Walk_proxy');
			
			$paypalTempId = $this->Paypal_proxy->addTempData( $this->session->userdata('member_registration_value') );
			if ($paypalTempId <= 0)
			{
				$this->session->unset_userdata('member_registration_value');
				redirect( base_url() . 'cmb/member_registration/registration_error/');
			}
			$this->session->unset_userdata('sessionobj_temp_id');
			$this->session->set_userdata('sessionobj_temp_id', $paypalTempId);
			
			$memberRegistrationValue = unserialize($this->session->userdata('member_registration_value'));
			$memberRegistrationValue = Member_registration_value::cast($memberRegistrationValue);
/*			
			$memberRegistrationValue = $this->session->userdata('member_registration_value');
			$paypalTempId = $this->Paypal_proxy->addTempData( $memberRegistrationValue );
						
			$memberRegistrationValue = unserialize($this->session->userdata('member_registration_value'));
			$memberRegistrationValue = Member_registration_value::cast($memberRegistrationValue);
*/
			$cmbRegHistoryId = $memberRegistrationValue->getCMBRegHistoryId();
			$urlKey = $this->Walk_proxy->getMemberURLKey( $cmbRegHistoryId );
			if ($urlKey == "")
			{
				redirect( base_url() . 'cmb/member_registration/registration_error/');
			}
			
			//Set temp_id for serialized registration value object in 'cmb_reg_history'
			$this->Walk_proxy->setCMBRegistrationTempId( $cmbRegHistoryId, $paypalTempId );
			
			$data['title'] = $this->Walk_proxy->getCurrentYear().'-'.($this->Walk_proxy->getCurrentYear()+1).' Member Registration Summary';
			$data['view'] = 'cmb/register/member_registration_summary_paypalonly_view';
			$data['memberRegistrationValue'] = $memberRegistrationValue;
			$data['paypal_form'] = $this->getPayPalForm( $memberRegistrationValue->getTotalRegistrationFee(), $paypalTempId, $this->Walk_proxy->getCurrentYear(), $memberRegistrationValue->getCMBRegHistoryId() );
			$data['urlKey'] = $urlKey;
			
			$this->load->view( self::$REGISTRATION_TEMPLATE, $data );
		}

		//Ask for payment for existing registration
		public function step3b()
		{
			$this->load->model('proxies/Paypal_proxy');
			$this->load->model('proxies/Walk_proxy');
			
			$memberRegistrationValue = unserialize($this->session->userdata('member_registration_value'));
			$memberRegistrationValue = Member_registration_value::cast($memberRegistrationValue);

			$cmbRegHistoryId = $memberRegistrationValue->getCMBRegHistoryId();
			if ($cmbRegHistoryId <= 0)
			{
				$this->session->unset_userdata('member_registration_value');
				redirect( base_url() . 'cmb/member_registration/registration_error/');
			}
			
			//Get object id from existing registration
			$paypalTempId = $this->Walk_proxy->getTempIDCMBRegistration( $cmbRegHistoryId );			
			if ($paypalTempId <= 0)
			{
				$this->session->unset_userdata('member_registration_value');
				redirect( base_url() . 'cmb/member_registration/registration_error/');
			}
			$this->session->unset_userdata('sessionobj_temp_id');
			$this->session->set_userdata('sessionobj_temp_id', $paypalTempId);
			
			$urlKey = $this->Walk_proxy->getMemberURLKey( $cmbRegHistoryId );
			if ($urlKey == "")
			{
				redirect( base_url() . 'cmb/member_registration/registration_error/');
			}
			
			$data['title'] = $this->Walk_proxy->getCurrentYear().'-'.($this->Walk_proxy->getCurrentYear()+1).' Member Registration Summary';
			$data['view'] = 'cmb/register/member_registration_summary_view';
			$data['memberRegistrationValue'] = $memberRegistrationValue;
			$data['paypal_form'] = $this->getPayPalForm( $memberRegistrationValue->getTotalRegistrationFee(), $paypalTempId, $this->Walk_proxy->getCurrentYear(), $memberRegistrationValue->getCMBRegHistoryId() );
			$data['urlKey'] = $urlKey;
			
			$this->load->view( self::$REGISTRATION_TEMPLATE, $data );
		}

		private function getPayPalForm( $amount, $paypalTempId, $curyear, $CMBRegHistoryId )
		{
			$this->load->library('Paypal_Lib');
			$this->load->model('proxies/Walk_proxy');
			
			//$this->Walk_proxy->setCMBRegistrationPending($CMBRegHistoryId);
			
		    $this->paypal_lib->add_field('return', site_url('/cmb/member_registration/success/'));
		    $this->paypal_lib->add_field('cancel_return', site_url('/cmb/member_registration/cancel/'));
		    $this->paypal_lib->add_field('notify_url', site_url('/cmb/member_registration/ipn/')); // <-- IPN url
		    $this->paypal_lib->add_field('custom', $paypalTempId); // <-- Verify return
	
		    $this->paypal_lib->add_field('item_name', $CMBRegHistoryId . ' - CMB ' . $curyear . '-' . ($curyear+1) . ' Registration');
		    $this->paypal_lib->add_field('item_number', $CMBRegHistoryId );
		    $this->paypal_lib->add_field('amount', $amount);
	
		    return $this->paypal_lib->paypal_form();			
		}
				
		public function member_registered()
		{
			$this->load->model('proxies/Walk_proxy');
			$data['title'] = 'You or Someone in your Household is Already Registered';
			$data['view'] = 'cmb/register/registration_members_exist_view';
			$data['curyear'] = $this->Walk_proxy->getCurrentYear();
			
			$this->load->view( self::$REGISTRATION_TEMPLATE, $data );
		}
				
		public function incomplete_registration()
		{
			$this->load->model('proxies/Walk_proxy');
			$data['title'] = 'Your Registration is Incomplete';
			$data['view'] = 'cmb/register/registration_incomplete_view';
			$data['curyear'] = $this->Walk_proxy->getCurrentYear();
			
			$this->load->view( self::$REGISTRATION_TEMPLATE, $data );
		}
				
		public function registration_error()
		{
			$this->load->model('proxies/Walk_proxy');

			$data['title'] = 'An error occurred during registration';
			$data['view'] = 'cmb/register/registration_error_view';
			$data['curyear'] = $this->Walk_proxy->getCurrentYear();
			
			$this->load->view( self::$REGISTRATION_TEMPLATE, $data );
		}

		public function registration_paid()
		{
			$this->load->model('proxies/Walk_proxy');

			$data['title'] = 'You have already paid for your CMB registration';
			$data['view'] = 'cmb/register/registration_paid_view';
			$data['curyear'] = $this->Walk_proxy->getCurrentYear();
			
			$this->load->view( self::$REGISTRATION_TEMPLATE, $data );
		}

		public function success()
		{
			$this->load->model('proxies/Walk_proxy');
			
			$data['title'] = 'Registration Success';
			$data['view'] = 'cmb/register/registration_success_view';
			$data['curyear'] = $this->Walk_proxy->getCurrentYear();
					
			$this->load->view( self::$REGISTRATION_TEMPLATE, $data );
		}
		
		public function pay_by_check( $urlKey )
		{
			$this->load->model('proxies/Walk_proxy');
			$this->load->model('proxies/Paypal_proxy');
			
			$currentyear = $this->Walk_proxy->getCurrentYear();

			$cmbRegHistoryId = $this->Walk_proxy->getCMBRegHistoryIdfromURLYear( $urlKey, $currentyear );
			if ($cmbRegHistoryId <= 0)
			{
				redirect( base_url() . 'cmb/member_registration/registration_error/');
			}
			
			$paypalTempId = $this->Walk_proxy->getTempIDCMBRegistration( $cmbRegHistoryId );			
			if ($paypalTempId <= 0)
			{
				redirect( base_url() . 'cmb/member_registration/registration_error/');
			}
			
			$memberRegistrationValue = unserialize($this->Paypal_proxy->getTempData( $paypalTempId ));
			$memberRegistrationValue = Member_registration_value::cast($memberRegistrationValue);
/*
			$memberRegistrationValue = unserialize($this->session->userdata('member_registration_value'));				
			$memberRegistrationValue = Member_registration_value::cast($memberRegistrationValue);
*/
			/*
			$total_fee = $this->Walk_proxy->getCMBTotalRegistrationFeefromURL( $urlKey );
			$CMBRegHistoryId = $this->Walk_proxy->getCMBRegHistoryIdfromURL( $urlKey );
			$memberRegistrationValue->setCMBRegHistoryId( $CMBRegHistoryId );
			*/
			
			$total_fee = $memberRegistrationValue->getTotalRegistrationFee();
			$cmbRegHistoryId = $memberRegistrationValue->getCMBRegHistoryId();
			
			//Update 'amount_paid' in 'cmb_reg_history' for check payment
			$tmp = $this->Walk_proxy->confirmCMBRegistrationCheck($cmbRegHistoryId, $total_fee);
			
			//Send an admin email to notify payment by check
			$this->Walk_proxy->sendMemberRegistrationByCheckAdminEmail( $memberRegistrationValue, $currentyear );

			//Send email to member with instructions on sending the check
			$this->Walk_proxy->sendMemberRegistrationByCheckEmail( $memberRegistrationValue, $currentyear );

			$paypalTempId = $this->session->userdata('sessionobj_temp_id');
			
			//Remove value object from temp table
			$this->Paypal_proxy->removeTempData( $paypalTempId );
			
			//Remove value object reference from registration
			$this->Walk_proxy->unSetCMBRegistrationTempId( $cmbRegHistoryId );
			
			$this->session->unset_userdata('sessionobj_temp_id');
			
			$data['title'] = 'Chimaya Mission Boston Registration - Payment by Check';
			$data['view'] = 'cmb/register/registration_paybycheck_view';
			$data['curyear'] = $currentyear;
			$data['total_fee'] = $total_fee;
					
			$this->session->unset_userdata('member_registration_value');

			$this->load->view( self::$REGISTRATION_TEMPLATE, $data );
		}
		
		public function success_nopay()
		{
			$this->load->model('proxies/Walk_proxy');
			
			$data['title'] = 'Registration Success for Life Member';
			$data['view'] = 'cmb/register/registration_success_nopay_view';
			$data['curyear'] = $this->Walk_proxy->getCurrentYear();
					
			$this->load->view( self::$REGISTRATION_TEMPLATE, $data );
		}
		
		public function cancel()
		{
			redirect( base_url() );
			die;
		}
		
		public function forgot_password()
		{
			$this->load->model('proxies/Walk_proxy');
			
			$data['title'] = 'Forgot Login Credentials';
			$data['view'] = 'cmb/register/forgot_password_view';
			$data['curyear'] = $this->Walk_proxy->getCurrentYear();
					
			$this->load->view( self::$REGISTRATION_TEMPLATE, $data );
		}
				
		public function ipn()
		{
			$this->load->model('proxies/Paypal_proxy');
			$this->load->library('Paypal_Lib');
			
			if( $this->paypal_lib->validate_ipn() ) 
			{
				$this->load->model('proxies/Person_proxy');
				$this->load->model('proxies/Walk_proxy');
				
				$memberRegistrationValue = unserialize($this->Paypal_proxy->getTempData( $this->paypal_lib->ipn_data['custom'] ));
				$memberRegistrationValue = Member_registration_value::cast( $memberRegistrationValue );

				//Update 'amount_paid' in 'cmb_reg_history' for Paypal
				$cmbRegHistoryId = $memberRegistrationValue->getCMBRegHistoryId();
				$tmp = $this->Walk_proxy->confirmCMBRegistration($cmbRegHistoryId, $memberRegistrationValue->getTotalRegistrationFee(), $this->paypal_lib->ipn_data['txn_id']);
				
				//Remove value object from temp table
				$this->Paypal_proxy->removeTempData( $this->paypal_lib->ipn_data['custom'] );
				
				//Remove value object reference from registration
				$this->Walk_proxy->unSetCMBRegistrationTempId( $cmbRegHistoryId );

				$this->session->unset_userdata('sessionobj_temp_id');
			
				//$msg = $this->paypal_lib->ipn_data['txn_id'].' , '.$memberRegistrationValue->getCMBRegHistoryId().' , '.$memberRegistrationValue->getPerson()->getFirstName();
				//$this->Walk_proxy->log_cmb_registration($msg);
				
				//Send email confirming payment and registration
				$this->Walk_proxy->sendMemberRegistrationConfirmEmailPaypal( $memberRegistrationValue, $this->paypal_lib->ipn_data['txn_id']);
			}
		}	
	}
?>